How to split a comma-separated string?
I have a String with an unknown length that looks something like this
"dog, cat, bear, elephant, ..., giraffe"
What would be the optimal way to divide this string at the commas so each word could become an element of an ArrayList?
For example
List<String> strings = new ArrayList<Strings>();
// Add the data here so strings.get(0) would be equal to "dog",
// strings.get(1) would be equal to "cat" and so forth.
Solution 1:
You could do this:
String str = "...";
List<String> elephantList = Arrays.asList(str.split(","));
Basically the .split()
method will split the string according to (in this case) delimiter you are passing and will return an array of strings.
However, you seem to be after a List of Strings rather than an array, so the array must be turned into a list by using the Arrays.asList()
utility. Just as an FYI you could also do something like so:
String str = "...";
ArrayList<String> elephantList = new ArrayList<>(Arrays.asList(str.split(","));
But it is usually better practice to program to an interface rather than to an actual concrete implementation, so I would recommend the 1st option.
Solution 2:
Well, you want to split, right?
String animals = "dog, cat, bear, elephant, giraffe";
String[] animalsArray = animals.split(",");
If you want to additionally get rid of whitespaces around items:
String[] animalsArray = animals.split("\\s*,\\s*");
Solution 3:
You can split it and make an array then access like array
String names = "prappo,prince";
String[] namesList = names.split(",");
you can access like
String name1 = namesList [0];
String name2 = namesList [1];
or using loop
for(String name : namesList){
System.out.println(name);
}
hope it will help you .
Solution 4:
A small improvement: above solutions will not remove leading or trailing spaces in the actual String. It's better to call trim before calling split. Instead of this,
String[] animalsArray = animals.split("\\s*,\\s*");
use
String[] animalsArray = animals.trim().split("\\s*,\\s*");
Solution 5:
First you can split names like this
String animals = "dog, cat, bear, elephant,giraffe";
String animals_list[] = animals.split(",");
to Access your animals
String animal1 = animals_list[0];
String animal2 = animals_list[1];
String animal3 = animals_list[2];
String animal4 = animals_list[3];
And also you want to remove white spaces and comma around animal names
String animals_list[] = animals.split("\\s*,\\s*");