I am trying to break string on delim “//”. My string also contains “/” and StringTokenizer giving strange result, it also break string on “/”.
String mStr = "abcd//aaa//32434//3/34343";
StringTokenizer tok = new StringTokenizer(mStr, "//");
while(tok.hasMoreTokens()){
System.out.println(tok.nextToken());
}
the result is
abcd
aaa
32434
3
34343
And the expected result is
abcd
aaa
32434
3/34343
Why this is happening and what is the solution of it? I do not want to replace “/” with other characters.
StringTokenizertakes both the tokens as separate, and tokenizes on both of them. So, it is tokenizing on both//and/, and hence the result.I would rather prefer
String#splitoverStringTokenizer. It’s easier to use, and has more options. It can takeRegexas parameter, and returns anarrayoftokenswhich you can use later on: –Output : –