Splitting a string with delimiters for Strings containing other characters with the same delimiter

StackOverflow https://stackoverflow.com/questions/15006954

Question

I'm trying to split a string like the one : "@WWP2-@POLUXDATAWWP3-TTTTTW@K826" to extract the @WWP2-@POLUXDATAWWP3-TTTTTW and the 826 strings when executing the snippet :

String expression = "@WWP2-@POLUXDATAWWP3-TTTTTW@K826";
        StringTokenizer tokenizer = new StringTokenizer(expression, "@K");
            if (tokenizer.countTokens() > 0) {
                while (tokenizer.hasMoreTokens()) {
                    System.out.println(tokenizer.nextToken());
                }
            }

while expecting the result to be

WWP2-POLUXDATAWWP3-TTTTTW
826

I'm getting:

WWP2-
POLUXDATAWWP3-TTTTTW
826

Any idea on how to get the exact two strings?

Was it helpful?

Solution

    String[] str = expression.split("@K");
    System.out.println(Arrays.toString(str));

Try String#split("@K");

Output:

[@WWP2-@POLUXDATAWWP3-TTTTTW, 826]

OTHER TIPS

StringTokenizer will use the given delimiter parameter as a set of chars if it contains more than one char. In your case, it will split your string by @ and by K, while K must not necessarily follow @.

String expression = "@WWP2-@POLUXDATAWWP3-TTTTTW@K826";

String [] strArr = expression.split("@K");

for( int i = 0; i < strArr.length; i++ ) {
    System.out.println( strArr[i] );
}

The StringTokenizer splits the string on all the single characters in the delimiter string, i.e. on @ and K.

Also see Why is StringTokenizer deprecated?.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top