Reputation: 1710
I am using String Tokenizer in my program to separate strings. Delimiter I am trying to use is ");". But I found out that StringTokenizer uses ) and ; as 2 different delimiters. But I want to use it as combined. How can I do it?
my code:
StringTokenizer st = new StringTokenizer(str,");");
String temp[] = new String[st.countTokens()];
while(st.hasMoreTokens()) {
temp[i]=st.nextToken();
i++;
}
Thanks
Upvotes: 1
Views: 4260
Reputation:
This will work for you.
import java.util.StringTokenizer;
public class StringTest {
/**
* @param args
*/
public static void main(String[] args) {
int i = 0;
String str = "one);two);three);four";
StringTokenizer st = new StringTokenizer(str, ");");
String temp[] = new String[st.countTokens()];
while (st.hasMoreTokens()) {
temp[i] = st.nextToken();
System.out.println(temp[i]);
i++;
}
}
}
Upvotes: 0
Reputation: 5311
As many of the answers have suggested, String.split() will solve your problem. To escape the specific sequence you're trying to tokenize on you will have to escape the ')' in your sequence like this:
str.split("\\);");
Upvotes: 2
Reputation: 3436
"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."
Thats what Sun's doc says.
String[] result = "this is a test".split("\\s");
Is the recommended way to tokenize String.
Upvotes: 0
Reputation: 237
You should try with the split(String regex) method from the String class. It should work just fine, and I guess it returns an array of Strings ( just like you seem to prefer). You can always cast to a List by using Arrays.asList() method.
Cheers, Tiberiu
Upvotes: 0
Reputation: 262834
As an alternative to String#split (StringTokenizer is deprecated), if you like Commons Lang, there is StringUtils#splitByWholeSeparator (null-safe, and no need to mess with regular expressions):
String temp[] = splitByWholeSeparator(str, ");" );
Upvotes: 2