Here is the code piece I have:
String current = scanner2.next();
String[] splitCurrent = current.split("\:", -1);
if(splitCurrent[1] != "") {.......
It's supposed to split a string into an array based on colons. So A:B:C: would become A,B,C where each is an element in the array.
However, when using something like New York Station:B:C:, it ends up splitting the string based on both colons (:) and spaces, so New, York, Station,B,C. Is there a way to use String.split without splitting around spaces so the end result is New York Station, B, C?
CodePudding user response:
All other issues with your code aside, the split()
method will do exactly what you are expecting if you remove the backslash before the colon. It will then ignore spaces and break on colon characters. Here's a working example:
public static void main (String[] args) {
String current = "New York Station:B:C";
String[] splitCurrent = current.split(":", -1);
for (String e: splitCurrent)
System.out.println(e);
}
Result:
New York Station
B
C
The second -1
argument to split()
is unnecessary. You'll get the same behavior if you remove that argument.
CodePudding user response:
You have to use scanner.nextLine()
instead of scanner.next()
You don't have to use .split("\:", -1);
but rather just .split(":");
private static void testing(Scanner scanner) {
String current = scanner.nextLine();
String[] args = current.split(":");
System.out.print("Input: " current);
System.out.println("Length: " args.length);
for (String c : args) {
System.out.print(c ", ");
}
}
Output:
Input: New York:A:B:C:Test Test
Length: 5
New York, A, B, C, Test Test,