0

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 /( - ) 
1
  • 2
    What is the value for mathExpression ? Commented Nov 14, 2013 at 11:32

3 Answers 3

1

No need to reinvent the wheel. You can just use String#getChars() or String#toCharArray().

Sign up to request clarification or add additional context in comments.

4 Comments

It's String#toCharArray().
I can not use char array because I will destroy my double values like i.e 67.4
@CodeSac Your question was about getting the characters of a string: "(...)I just need to get each and every char in this string one by one(...)"! That's exactly what the code in our answers do!
@CodeSac Sorry, your question is "I just need to get each and every char in this string one by one", I don't see what relevance what the chars actually are has.
0

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

Comments

0

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

2 Comments

@m0skit0 Maybe. But usually you want to do something with the single chars, so in the end you will have to iterate. So why not directly?
Maybe, maybe not, we don't know what the OP wants to do with the array actually.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.