Rafat Rifaie Rafat Rifaie - 2 months ago 9
Java Question

How to split a string that has spaces

I have this code, that lets the user enter a string with 2 parts separated by the character (-) and the inputted string, would be split into two different parts, and then output those two parts on the screen separated by a comma.

public class Test
{
public static void main(String[] args)
{
java.util.Scanner scanner = new java.util.Scanner(System.in);

String part = "";

System.out.println("Please enter the 2-part string to be split: ");
part = scanner.next();

String[] parts = part.split("-");
String part1 = parts[0];
String part2 = parts[1];

System.out.print("," + part1 + "," + part2);

scanner.close();
}

}


Now lets say the user enterd


aaa-222


the outcome would be


aaa,222


What if i want to enter a string that has spaces, like this


i love you-i hate you


how do i split (i love you) and (i hate you) ?
I get this error with the code above.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at tutorial.Test.main(test.java:17)


PS. the split parts should include the whitespace.

Answer

Instead of using

part = scanner.next();

https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next()

use

part = scanner.nextLine();

https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()

next, only reads in to the end of the token. where as nextLine reads until the user goes to the next line (presses enter)