4

I am trying to split the input sentence based on space between the words. It is not working as expected.

public static void main(String[] args) {
    Scanner scaninput=new Scanner(System.in);
    String inputSentence = scaninput.next();
    String[] result=inputSentence.split("-");
    // for(String iter:result) {
    //     System.out.println("iter:"+iter);
    // }
    System.out.println("result.length: "+result.length);
    for (int count=0;count<result.length;count++) {
        System.out.println("==");
        System.out.println(result[count]);
    }
}

It gives the output below when I use "-" in split:

fsfdsfsd-second-third
result.length: 3
==
fsfdsfsd
==
second
==
third

When I replace "-" with space " ", it gives the below output.

first second third
result.length: 1
==
first

Any suggestions as to what is the problem here? I have already referred to the stackoverflow post How to split a String by space, but it does not work.

Using split("\\s+") gives this output:

first second third
result.length: 1
==
first
Community
  • 1
  • 1
Zack
  • 2,078
  • 10
  • 33
  • 58

4 Answers4

8

Change

scanner.next()

To

scanner.nextLine()

From the javadoc

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

Calling next() returns the next word.
Calling nextLine() returns the next line.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
7

The next() method of Scanner already splits the string on spaces, that is, it returns the next token, the string until the next string. So, if you add an appropriate println, you will see that inputSentence is equal to the first word, not the entire string.

Replace scanInput.next() with scanInput.nextLine().

Hoopje
  • 12,677
  • 8
  • 34
  • 50
1

The problem is that scaninput.next() will only read until the first whitespace character, so it's only pulling in the word first. So the split afterward accomplishes nothing.

Instead of using Scanner, I suggest using java.io.BufferedReader, which will let you read an entire line at once.

ruakh
  • 175,680
  • 26
  • 273
  • 307
0

One more alternative is to go with buffered Reader class that works well.

String inputSentence;

            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            inputSentence=br.readLine();

            String[] result=inputSentence.split("\\s+");
rintln("result.length: "+result.length);

            for(int count=0;count<result.length;count++)
            {
                System.out.println("==");
                System.out.println(result[count]);
            }

        }
Yash Varshney
  • 365
  • 1
  • 5
  • 16