简体   繁体   中英

StringTokenizer separate tokens using a char

How do I separate tokens in a StringToekenizer object taking a string s as a parameter?

so:

String s = input.readLine();
char tokenSeparator = ' '; //can be any value other than white space.
StringTokenizer str = new StringTokenizer(s);
//separate tokens by the variable char tokenSeparator;
while (str.hasMoreTokens) ...

From the Javadoc :

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() , ie:

String s = input.readLine();
String[] tokens = s.split(" ");

Check the javadoc . You can see a parameterized constructor as

public StringTokenizer(String str, String delim)

This is what you require here.

Example

String msg = "http://100.15.111.60:80/";
char tokenSeparatpor = ':';
StringTokenizer st = new StringTokenizer(msg,tokenSeparatpor+"");
while(st.hasMoreTokens()){
    System.out.println(st.nextToken());
}

Output

http
//100.15.111.60
80/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM