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 ?
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>
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());
}
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));
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.