1

I am using the StringToken class to tokenize my input as follows:

StringTokenizer tokens = new StringTokenizer(input); n = tokens.countTokens(); a = tokens.nextToken() 

However, I found that split is more efficient, is there a way how to get the number of tokens (instead of countTokens) and a way to get the next token if I use split?

1

3 Answers 3

0

You can do this:

String str = "aa,bb,cc,dd"; String[] token = str.split(","); System.out.println("Size of tokens: " + token.length); //Printing out all tokens for(int x=0; x<token.length; x++) //A few different ways to print out the token values System.out.println(token[x]); 

string.split() method will return you with a string array. So now you can treat each token element as a string array element. In the above codes, token is just a String array.

OUTPUT:

Size of tokens: 4 aa bb cc dd 

Is this what you wanted?

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

7 Comments

And a way to get the next token if I use split.
Actually I don't quite get what he meant by get next token.
aa is the first token. bb is the second token. The next token after bb is cc.
i mean get the next word, like if i have hello world i need to get first hello then world
Wouldn't token[0], token[1]..etc get the thing you want? Am I interpreting your question wrongly?
|
0

This might be what you looking for:

String str = "A,B,C,D"; String[] token = str.split(","); ArrayList<String> tokList = new ArrayList<String>(Arrays.asList(token)); Iterator<String> tok = tokList.iterator(); while(tok.hasNext()) //Check whether next element exsit System.out.print(tok.next()); //Print out the token string 1 by 1 

Program Output: ABCD

Comments

0

Assume you have String abcd = "a-b-c-d"; You can perform a split on this one. You'll get: String[] stringArray = abcd.split("-"); If you have the StringArray, you could get the size by using stringArray.length (and save the result to an int. If you want to get the "next token", you can simply iterate over the array:

for (int i = 0; i < stringArray.length; i++) { String tempString = stringArray[i]; //do something with the String } 

Is that what you are looking for?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.