Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string with space being the delimiter using Scanner

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
like image 811
Zack Avatar asked Dec 05 '22 04:12

Zack


2 Answers

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.

like image 124
Bohemian Avatar answered May 16 '23 08:05

Bohemian


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().

like image 21
Hoopje Avatar answered May 16 '23 09:05

Hoopje