-4

Possible Duplicate:
How do I split a string with any whitespace chars as delimiters?

Yes, I tried to search it on google and stackoverflow, but no good results. I have a string, lets say: "Lets do some coding in Java" and I would like to got strings (split it on whitespaces):

Lets, do, some, coding, in, Java

I used string.split("\\s") for this, but know I need to use regex instead. Any ideas?

Community
  • 1
  • 1
IOException
  • 53
  • 1
  • 1
  • 1

2 Answers2

12
String str = "Hello How are you";
String arrayString[] = str.split("\\s+") 

Please use this

arshajii
  • 127,459
  • 24
  • 238
  • 287
sunleo
  • 10,589
  • 35
  • 116
  • 196
3

to specify space as splitting char, you can pass " " as parameter to String#split. Example:

String test="Lets do some coding in Java";
    for(String token : test.split(" "))
        System.out.println(token);
avalori
  • 427
  • 2
  • 5
  • 17
  • 2
    Better to use `\\s+` for splitting on any number of spaces. – Rohit Jain Nov 21 '12 at 15:31
  • 1
    it won't work it has multiple space.String s ="hello sorry". – sunleo Nov 21 '12 at 15:32
  • It has one space, my code would split "hello sorry" in "hello" and "sorry" (try). It won't handle the case in which the test phrase has multiple spaces, as @RohitJain pointed out. Your solution is better than mine because is more general. – avalori Nov 21 '12 at 15:52