2

Is there anyway we can directly access a certain(lets say 20th) element in a stringTokenizer. Every now and then I need only a certain element from it and do not need others, yet I have to traverse through all elements.

EDIT: I also want to ignore empty elements.

Am I missing something?

jem
  • 257
  • 4
  • 14

3 Answers3

5

You can use String.split for that instead of a Tokenizer.

For example:

String[] split = "you string is splitting".split(" ");
split[2];  // random access to the 3rd element of split    

Of course, you will need to check that your split actually has that many elements before accessing its subindex.

Xipo
  • 1,765
  • 1
  • 16
  • 23
Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
3

You could try Apache Commons Lang's StringUtils class, which can split a string while ignoring empty elements and handling null strings for you.

A tokenizer would have to read at least n tokens in order to determine which is the n-th one. Thus it might be easier to just create a string array using String#split() or StringUtils.split(...).

Note that I'd prefer StringUtils.split(...) since it doesn't return empty elements if I don't want them, i.e. StringUtils.split(",a,b,c;;d,e,,f",";,"); would return ["a","b","c","d","e","f"] whereas String#split() would return ["","a","b","c","","d","e","","f"]

Thomas
  • 87,414
  • 12
  • 119
  • 157
0

Tokenizer is meant to access elements sequentially (kinda like a LinkedList). You have to go through all the tokens and store them in some kind of random-access collection (ArrayList), or use another method to split your original string / stream.

Guillaume
  • 22,694
  • 14
  • 56
  • 70