JAVA : Alternatives to StringTokenizer class

,

I am currently using the StringTokenizer ( java.util.StringTokenizer ) class in Java every time I encounter input wherein more than one input value is on the same line.

( Eg : 2 3 10 9 )

It appears to me that StringTokenizer is actually quite slow, and I get TLE even in situations where I should not be getting it.

Now I know that for large input-output problems, the Scanner class ( java.util.Scanner ) is not an option, since it is also too slow. Any alternatives that I can use ? Any suggestions would be appreciated. Thank you :slight_smile:

3 Likes

I use the split method from the String class. For input I use BufferedReader.

Something like this:

// define BufferedReader
BufferedReader myReader = new BufferedReader(new InputStreamReader(System.in));

// You will be needing a string and a string array. The latter
// will keep individual tokens.
String singleLine = myReader.readLine();
String[] brokenLine = singleLine.split(" ");

// brokenLine now contains a single token from singleLine
// in each of its elements.

// Getting an integer array from brokenLine
int[] myNumbers = new int[brokenLine.length];
for(int i = 0; i < brokenLine.length; i++)
    myNumbers[i] = Integer.parseInt(brokenLine[i]);

Hope it helps.

3 Likes

Thank you so much ! :slight_smile:

Yes the BufferedReader works with the split function… I only get TLEs when my algorithm is not efficient enough…

1 Like

I’m very happy for the result, and for that my ranking on the long contest now is better than the short, custom assignment writing service but I think this is the true… I feel I’m not good at the short.

I have some questions too: