user1766888
user1766888

Reputation: 409

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) ...

Upvotes: 1

Views: 1242

Answers (2)

mtk
mtk

Reputation: 13709

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/

Upvotes: 2

durron597
durron597

Reputation: 32323

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(), i.e.:

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

Upvotes: 3

Related Questions