user1285928
user1285928

Reputation: 1476

How to extract strings

I'm new to Java programming. I want to write simple Java network protocol. I want to send this string to remote Java host, for example:

230 computer delete reboot exit

The problem that I cannot resolve is how I can extract the strings one by one and put it into array? And the biggest mystery to me is how I do this if I have strings with different length? Thank you for your help!

PS: Can I send directly entire array not just simple strings?

PS 2: What if I have Java server and C client? As far as know only strings can be used to exchange data between both sides?

Upvotes: 1

Views: 133

Answers (3)

dacwe
dacwe

Reputation: 43504

You can either:

  1. Split the strings using String.split method

    String text = "230 computer delete reboot exit";
    String[] split = text.split("\\s");
    
  2. Using a Pattern and a Matcher

    String text = "230 computer delete reboot exit";
    Pattern p = Pattern.compile("(.*)\\s+(.*)\\s+(.*)\\s+(.*)\\s+(.*)");
    Matcher m = p.matcher(text);
    if (m.matches()) {
        String first = m.group(1);
        String second = m.group(2);
        ....
    
  3. Using a Scanner class

    Scanner s = new Scanner(text);
    int firstNumber = s.nextInt(); // 230
    String secondText = s.next(); // computer
    ....
    

The second and the third choice could be superior if read stuff from a stream.

Or some other method... :)

Upvotes: 4

Jack
Jack

Reputation: 133567

You can send directly an array by using serialization through ObectInputStream and ObjectOutputStream.

But I suggest you to use your own classes to encapsulate messages. Eg

class NetworkMessage {
  int code;
  String param1;
  String param2;
  ..
}

So that it's more object oriented and structured. Sending just strings is not a good design, especially if the protocol grows in complexity.

Regarding splitting the string just use String.split(String regex) method but it's not a good solution.

Upvotes: 3

Kazekage Gaara
Kazekage Gaara

Reputation: 15052

String input = "230 computer delete reboot exit";
String s[] = input.split("\\s+");

// now s[0] = 230 s[1] = computer

Read more on String.split().

And the regex used here \\s+ is equal to any whitespace. Read this for further information.

Upvotes: 4

Related Questions