Rafat Rifaie Rafat Rifaie - 1 year ago 85
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);



Now lets say the user enterd


the outcome would be


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 Source

Instead of using

part = scanner.next();



part = scanner.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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download