Reputation:
I am tryting to split string by "," using StringTokenizer but not able to get whole values , token count shows 3 but printing only two elements, i have added my code below if i have tried with two other inputs "Ravi,Tuti,786" - same output "Ravi,Tuti,786,pincode" getting three tokens not last one
public class Tokenizer{
public static void main(String[] args){
String str = "Ravi,Tuti,786";//survival of fittest,journey to get job,update skill,try,get job";
StringTokenizer stk = new StringTokenizer(str,",");
System.out.println(stk.countTokens());
for(int i=0;i<=stk.countTokens();i++){
System.out.println(stk.nextToken());}
}
}
output is
3
Ravi
Tuti
Upvotes: 1
Views: 373
Reputation: 12819
The countTokens()
method returns:
the number of tokens remaining in the string using the current delimiter set.
So in your if
loop it keeps getting evaluating and returning smaller numbers. To prevent this you can resolve it to a variable
int length = stk.countTokens();
for(int i=0;i<length;i++){
System.out.println(stk.nextToken());
}
If you do not wish to introduce another variable you can start i
at what countTokens()
returns and then loop until i
is more that zero (While subtracting from i
instead of adding)
for(int i=stk.countTokens();i>0;i--){
System.out.println(stk.nextToken());
}
Output:
3
Ravi
Tuti
786
Upvotes: 1
Reputation: 20931
You should use hasTokens()
method.
for( ; stk.hasMoreTokens() ; ) {
System.out.println(stk.nextToken());
}
Upvotes: 1
Reputation: 27812
Use hasMoreTokens()
with nextToken
:
public class Tokenizer{
public static void main(String[] args){
String str = "Ravi,Tuti,786";//survival of fittest,journey to get job,update skill,try,get job";
StringTokenizer stk = new StringTokenizer(str,",");
System.out.println(stk.countTokens());
while (stk.hasMoreTokens()) {
System.out.println(stk.nextToken());
}
}
}
The problem with your approach is that you are running countTokens
in the for
loop, which changes after nextToken
is called.
If you want to use a for
loop, you need to save the token count to a variable:
int numTokens = stk.countTokens();
for (int i = 0; i < numTokens; i++) {
System.out.println(stk.nextToken());
}
Upvotes: 1