Reputation: 1669
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?
Upvotes: 1
Views: 396
Reputation: 13631
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?.
Upvotes: 0
Reputation: 48807
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 @
.
Upvotes: 0
Reputation: 12843
String[] str = expression.split("@K");
System.out.println(Arrays.toString(str));
Try String#split("@K");
Output:
[@WWP2-@POLUXDATAWWP3-TTTTTW, 826]
Upvotes: 4