Reputation: 311
I have a complex string and I just need to get each and every char in this string one by one. Here what I did, but at one place I am getting both /( I know what because there is a no delimiter between them. How can I overcome this?
Hear is my string : 3 + 4 * 2 / ( 1 - 5 )
My code:
StringTokenizer tokenizer = new StringTokenizer(mathExpression , "+-x/()");
StringTokenizer tokenizer2 = new StringTokenizer(mathExpression , "123456789");
while (tokenizer.hasMoreElements()) {
System.out.println(tokenizer.nextToken());
}
while (tokenizer2.hasMoreElements()) {
System.out.println(tokenizer2.nextToken());
}
Output :
3
4
2
1
5
+
x
/(
-
)
Upvotes: 0
Views: 7328
Reputation: 25874
No need to reinvent the wheel. You can just use String#getChars()
or String#toCharArray()
.
Upvotes: 1
Reputation: 14943
An instance of StringTokenizer behaves in one of two ways, depending on whether it was created with the returnDelims flag having the value true or false:
•If the flag is false, delimiter characters serve to separate tokens. A token is a maximal sequence of consecutive characters that are not delimiters.
•If the flag is true, delimiter characters are themselves considered to be tokens. A token is thus either one delimiter character, or a maximal sequence of consecutive characters that are not delimiters.
http://docs.oracle.com/javase/6/docs/api/java/util/StringTokenizer.html
StringTokenizer(mathExpression , "+-x/()", true);
Upvotes: 0
Reputation: 24464
Why do you use a StringTokenizer
? Just iterate the String
:
for(int i = 0; i < myString.length(); i++) {
char c = myString.charAt(i);
// do something with c
}
If you're not directly interested in single chars but want to have all of them at once, you can also request a char[]
from the string:
char[] chars = myString.toCharArray();
(Note that this will return a copy of the String
-internal char array, so if you just want to process single chars, the first method might be less memory- and performance-intensive).
Upvotes: 0