0
String str = "00 01 02";
String[] strings = str.split(" ");

This works as expected. But if I want to add Tab to the list, it stops working, returning the whole string:

String[] strings = str.split(" \t");

So, as usual, I ask to translate from C# to Java...

Alex F
  • 42,307
  • 41
  • 144
  • 212
  • 2
    Do you want all white-spaces or just space and tab? – Peter Lawrey Oct 01 '12 at 08:56
  • the split method splits about a regular expression. To split at multiple delimiters you may want to use the StringTokenizer class object. But you will need to use a loop to create your desired string array. – Victor Mukherjee Oct 01 '12 at 09:14

5 Answers5

4
String[] strings = str.split("\\s+");
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
2

You could try:

str.split("\\s+")

It will split on any space and will remove all extra space. To simply include tab, use this:

str.split("[ \\t]")
Ivan Koblik
  • 4,285
  • 1
  • 30
  • 33
  • Using `\t` rather than `\\t` should be fine. – Peter Lawrey Oct 01 '12 at 08:59
  • @PeterLawrey True, if `\t` is used then java compiler will substitute it with `U+0009` if `\\t` is used then regular expression engine will interpret is as `U+0009`. More info [here](http://stackoverflow.com/questions/3762347/understanding-regex-in-java-split-t-vs-split-t-when-do-they-both-wor). – Ivan Koblik Oct 01 '12 at 09:44
0

String.split() takes a regular expression:

Splits this string around matches of the given regular expression.

0
String s = "Hello this is Vivek";

String[] sArr = s.split("\\s+");

Voila its done..!!!!!

Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
0

First argument of the split method is a regular expression. That means, you have to fill it with the regular expression it suits you the best. If you read here: http://www.regular-expressions.info/reference.html you'll see there is a token that suits your requisites the best: \s . It matches whitespaces, tabs and linebreaks (I don't know if you want to cover linebreaks, but chances are you need).

The other question is: should the strings be split by exactly one whitespace/tab? What should happen when you have "00 11 2"? If this is something you want, you'll need to use the +, meaning you want to split by one or more whitespaces/tabs.

Hence, my proposed solution for you:

str.split("\\s+") 
ChuckE
  • 5,610
  • 4
  • 31
  • 59