Reputation: 123
I am trying to filter out commas and spaces from file input. I am returning a line of input(example below and passing that line to a method which is filtering out the commas and leading and trailing spaces)
John Paul Claurigh, Craig Megan, Bob a’ Chores
should filter to three separate strings in the an array.
John Paul Claurigh
Craig Megan
Bob a’ Chores
My problem is not getting rid of the commas but eliminating the leading and trailing spaces.
public void listConverter(String list){
String[] array=listConverter.split(",");
for(int i=0; i<array.length; i++){
addSubject(array[i]);
}
Can I use the split method to get rid of the leading and trailing spaces ?
Upvotes: 2
Views: 1432
Reputation: 1606
A java 8 rendition
String fileInput = "John Paul Claurigh, Craig Megan , Bob a’ Chores ";
List<String> namesList = Pattern.compile(",\\s")
.splitAsStream(fileInput)
.map(name -> name.trim())
.collect(Collectors.toList());
namesList.forEach(name -> System.out.println("NAME: " + name));
OUTPUT
NAME: John Paul Claurigh
NAME: Craig Megan
NAME: Bob a’ Chores
Upvotes: 0
Reputation: 727
You can try this:
public void listConverter(String list){
String[] array=listConverter.split("\\s*,\\s*");
for(int i=0; i<array.length; i++){
addSubject(array[i]);
}
It will split on comma with or without any leading/trailing whitespaces.
Upvotes: 0
Reputation: 98881
Your code seems correct, just use trim() to remove the leading/ending spaces
public void listConverter(String list){
String[] array=listConverter.split(",");
for(int i=0; i<array.length; i++){
addSubject(array[i].trim());
}
Upvotes: 1
Reputation: 37023
Try something like:
String[] array = s.split("\\s*,\\s*");
Which means split by any number (0..n) spaces before or after comma (,).
Output:
<John Paul Claurigh>
<Craig Megan>
<Bob a’ Chores>
Upvotes: 2
Reputation: 5629
A simple split with a space after comma is more than enough
String s = "John Paul Claurigh, Craig Megan, Bob a’ Chores";
String[]tokens = s.split(", ");//note the space after comma.
System.out.println(Arrays.toString(tokens));
Upvotes: 0