Question

I have two types of Strings

command1|Destination-IP|DestinationPort
Command2|Destination-IP|DestinationPort|SourceIP|SourcePort|message

I tried to split the String to get the variables I started coding like this but not sure that it's the best way

public String dstIp="";
    public String dstPort="";
    public String srcIp="";
    public String scrPort="";
    public String message="";
    public String command="";

int first = sentence.indexOf ("|"); 


                if (first > 0)
                {

                    int second = sentence.indexOf("|", first + 1);
                    int third = sentence.indexOf("|", second + 1);

                 command = sentence.substring(0,first);
                 dstIp=    sentence.substring(first+1,second);
                 dstPort= sentence.substring(second+1,third);

Shall I continue in this way? Or maybe use regular expression? And if the String is

command1|Destination-IP|DestinationPort

I get an error because there are no third |

Était-ce utile?

La solution 2

Better to split your input by pipe symbol here:

String[] tokens = sentence.split( "[|]" ); // or sentence.split( "\\|" )

Then check for # of tokens by checking tokens.length and act accordingly.

Autres conseils

Take a look at the String.split method:

String line = "first|second|third";
String[] splitted = line.split("\\|");
for (String part: splitted) {
    System.out.println(part);
}

Side note: since "|" character has a special meaning (basically "|" means OR) in the regular expression syntax, one should escape it with the backslashes.

Actually it's pretty interesting to look at the results of the unescaped version "first|second|third".split("|").

Regular expression "|" translates into english as "empty string or empty string" and matches the string at any position. "first|second|third".split("|") returns an array of length 19: {"", "f", "i", "r", ..., "d"}

Use the Java function split(), which manages exactly what you're looking for!

Example code:

String test = "bla|blo|bli";
String[] result = test.split("\\|");

Use split with \\| as an argument. It returns a String[] which will have the different parts of the |-split String.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top