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?

user4345738
  • 181
  • 8
  • Strange, StringTokenizer should be as twice fast/effcient, see http://stackoverflow.com/questions/19677919/difference-between-using-stringtokenizer-and-string-split – Shmil The Cat Dec 11 '14 at 15:35

3 Answers3

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?

user3437460
  • 16,235
  • 13
  • 52
  • 96
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

user3437460
  • 16,235
  • 13
  • 52
  • 96
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?

X-Fate
  • 323
  • 4
  • 13