Reputation: 2208
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
Upvotes: 5
Views: 16417
Reputation: 375
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]);
}
}
Upvotes: 0
Reputation: 425003
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.
Upvotes: 8
Reputation: 12932
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()
.
Upvotes: 7
Reputation: 183290
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.
Upvotes: 1