Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java StringTokenizer unexpected results

i have the following code which will tokenize the string to create list of Objects:

import java.util.StringTokenizer;


public class TestStringTokenizer {
    private final static String INTERNAL_DELIMETER = "#,#";
    private final static String EXTERNAL_DELIMETER = "#|#";
    public static void main(String[]aregs){
        String test= "1#,#Jon#,#176#|#2#,#Jack#,#200#|#3#,#Jimmy#,#160";
        StringTokenizer tokenizer = new StringTokenizer(test, EXTERNAL_DELIMETER);
        while(tokenizer.hasMoreElements()){
            System.out.println(tokenizer.nextElement());
            //later will take this token and extract elements
        }
    }
}

What i expected output was
1#,#Jon#,#176
2#,#Jack#,#200
3#,#Jimmy#,#160

What i got was : 1
,
Jon
,
176
2
,
Jack
,
200
3
,
Jimmy
,
160

if i change the internal delimeter to some thing like , it will work properly why is this behavior happening ?

like image 390
A.Alqadomi Avatar asked Aug 08 '26 22:08

A.Alqadomi


1 Answers

AccordIng to the StringTokenizer JavaDocs

http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

Use String.split instead:

String[] strArr = stringToSplit.split(INTERNAL_DELIMETER);

The only change you need to make is that the or-pipe ("|") in EXTERNAL_DELIMETER is a special regular expression character, and must be escaped: "\\|".

More information can be found in the String.split Javadoc:

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)

like image 149
aliteralmind Avatar answered Aug 11 '26 11:08

aliteralmind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!