-4

In my string, i want to tokenize string on the basis of two or more spaces.

E.x.

String str = "I am  Chaitanya Gadam.      Split   this string."
StringTokenizer tokenizer = new StringTokenizer(str);
while (tokenizer.hasMoreTokens()) 
{
    String token = tokenizer.nextToken();
    System.out.println("==Token== : "+token);
}

I am getting out put as :

==Token== : [I]
==Token== : [am]
==Token== : [Chaitanya]
==Token== : [Gadam.]
==Token== : [split]
==Token== : [this]
==Token== : [string.]

But desired Output should be :

==Token== : [I am]
==Token== : [Chaitanya Gadam.]
==Token== : [split]
==Token== : [this string.]

2 Answers2

2

You can use this regex in the String.split(regex) method.

String[] tokens = str.split("  +");

Update:-

If you need to remove the leading and trailing white spaces, trim() it and then split your String.

str = str.trim();
Rahul
  • 44,383
  • 11
  • 84
  • 103
  • Another problem is that if my string have extra white space at the begining then i get output as, final String src = " I am Chaitanya Gadam. Split this srting."; [, I am, Chaitanya Gadam., Split, this srting.] – Chaitanya Gadam Apr 03 '13 at 08:28
  • but reqiured output is [I am, Chaitanya Gadam., Split, this srting.] So i am trying to use string tokenizer. – Chaitanya Gadam Apr 03 '13 at 08:30
  • Check my update. Use `trim()`. – Rahul Apr 03 '13 at 08:32
0

This should work-

    String[] array = str.split("\\s{2,}");
    for (String word : array) {
        System.out.println(word);
    }
Sudhanshu Umalkar
  • 4,174
  • 1
  • 23
  • 33