How to split a comma-separated string?

Go To StackoverFlow.com

175

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.
2012-05-17 07:43
by James Fazio
use method split("spliting char") it splits your string nad method will create string-array with splitted words - Simon Dorociak 2012-05-17 07:46


297

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 = (ArrayList<String>)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.

2012-05-17 07:45
by npinti
@JamesFazio: The .split method is one of the most handy methods in the String class, I would recommend you check out the link for the JavaDocs I have included in my answer ;) - npinti 2012-05-17 07:52
Thanks for the very thorough answer - James Fazio 2012-05-17 08:02
Keep in mind this won't trim the values so strings.get(1) will be " cat" not "cat - Alb 2013-06-28 15:33
str.split accepts regex so you can use str.split(",[ ]*"); so you remove commas and spaces after commas - vertti 2013-10-31 08:38
A comma delimited file (csv) might have a a comma in quotes, meaning it's not a delimiter. In this case Split will not work - Steven Trigg 2014-03-08 02:35
The second option requires as cast to ArrayList<String> - C_B 2014-08-28 09:57
If you need to keep empty entries (eg.for consistent array length) use split(",",-1) as per http://stackoverflow.com/questions/14602062/java-string-split-removed-empty-value - Fast Engy 2015-07-16 02:16
In this case you have to be careful with empty substring. That is ";;;".split(";") will produce empty arra - Michal Pasinski 2016-05-09 16:31
Great Answer 100% working. Thanks, Please keep it u - Pir Fahim Shah 2017-06-06 11:48
What if you would like to store the resulting items in a set rather than a list - Moses Kirathe 2018-03-11 16:07
@MosesKirathe: You should be able to do something like: new HashSet<String>(Arrays.asList(str.split(","))); - npinti 2018-03-12 11:55


141

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*");
2012-05-17 07:45
by Tomasz Nurkiewicz
Yes that is part of the solution. The OP seems to be after a List of Strings, not an array - npinti 2012-05-17 07:46
@npinti: yep, +1 to you, you were faster and I didn't want to copy your Arrays.asList() idiom - Tomasz Nurkiewicz 2012-05-17 07:47
+1 great point about the whitespace removal - HDave 2013-07-05 16:44
I kept thinking for 10 hours, then searched SO. didn't know that it is so easy to .split() - DeathRs 2015-12-12 02:55
What if you would like to store the resulting split items in a set rather than an in an Array - Moses Kirathe 2018-03-11 16:08
Its working fine and less line of codes - Parth Patel 2018-06-28 12:34


19

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 = names[0];
String name2 = names[1];

or using loop

for(String name : namesList){
System.out.println(name);
}

hope it will help you .

2016-01-31 08:37
by Prappo Prince


17

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*");
2013-12-11 12:17
by user872858
for ur second line, if we use trim() then we don't need space split like ("\\s*,\\s*") just use (","); this will results same - W I Z A R D 2015-01-10 05:13
I'm not sure of that @WIZARD because trim remove only the left and right space of the string, but not the space in it. So the trim(" string, with , space ") will be "string, with , space" - Thomas Leduc 2015-05-13 08:08
@ThomasLeduc if string is like this "dog, cat, bear, elephant, giraffe" then no need of trim() and in ur case if use trim() then out put will be "string,with,space" not this "string, with , space"W I Z A R D 2015-05-13 08:34
trim() will remove all spaces not just left and right space of strin - W I Z A R D 2015-05-13 08:39
Do you test it ? because I've just wrote a program java and the string " string, with , space ".trim() return "string, with , space". Like javadoc says : returns a copy of the string, with leading and trailing whitespace omitted. You are wrong and @user872858 is right - Thomas Leduc 2015-05-13 08:55


3

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*");
2015-04-30 09:21
by sam


3

For completeness, using the Guava library, you'd do: Splitter.on(",").split(“dog,cat,fox”)

Another example:

String animals = "dog,cat, bear,elephant , giraffe ,  zebra  ,walrus";
List<String> l = Lists.newArrayList(Splitter.on(",").trimResults().split(animals));
// -> [dog, cat, bear, elephant, giraffe, zebra, walrus]

Splitter.split() returns an Iterable, so if you need a List, wrap it in Lists.newArrayList() as above. Otherwise just go with the Iterable, for example:

for (String animal : Splitter.on(",").trimResults().split(animals)) {
    // ...
}

Note how trimResults() handles all your trimming needs without having to tweak regexes for corner cases, as with String.split().

If your project uses Guava already, this should be your preferred solution. See Splitter documentation in Guava User Guide or the javadocs for more configuration options.

2015-09-02 20:40
by Jonik


2

Can try with this worked for me

 sg = sg.replaceAll(", $", "");

or else

if (sg.endsWith(",")) {
                    sg = sg.substring(0, sg.length() - 1);
                }
2017-03-14 13:43
by Tarit Ray


0

Remove all white spaces and create an fixed-size or immutable List (See asList API docs)

final String str = "dog, cat, bear, elephant, ..., giraffe";
List<String> list = Arrays.asList(str.replaceAll("\\s", "").split(","));
// result: [dog, cat, bear, elephant, ..., giraffe]

It is possible to also use replaceAll(\\s+", "") but maximum efficiency depends on the use case. (see @GurselKoca answer to Removing whitespace from strings in Java)

2016-09-09 19:56
by sdc


0

You can use something like this:

String animals = "dog, cat, bear, elephant, giraffe";

List<String> animalList = Arrays.asList(animals.split(","));

Also, you'd include the libs:

import java.util.ArrayList;
import java.util.Arrays; 
import java.util.List;
2017-02-20 21:36
by Diego Cortes


0

Use this :

        List<String> splitString = (List<String>) Arrays.asList(jobtype.split(","));
2018-08-30 11:53
by Abhishek Sengupta


0

In Kotlin,

val stringArray = commasString.replace(", ", ",").split(",")

where stringArray is List<String> and commasString is String with commas and spaces

2018-09-25 05:49
by KishanSolanki124


0

in build.gradle add Guava

    compile group: 'com.google.guava', name: 'guava', version: '27.0-jre'

and then

    public static List<String> splitByComma(String str) {
    Iterable<String> split = Splitter.on(",")
            .omitEmptyStrings()
            .trimResults()
            .split(str);
    return Lists.newArrayList(split);
    }

    public static String joinWithComma(Set<String> words) {
        return Joiner.on(", ").skipNulls().join(words);
    }

enjoy :)

2019-01-21 11:43
by panayot_kulchev_bg


-1

There is a function called replaceAll() that can remove all whitespaces by replacing them with whatever you want. As an example

String str="  15. 9 4;16.0 1"
String firstAndSecond[]=str.replaceAll("\\s","").split(";");
System.out.println("First:"+firstAndSecond[0]+", Second:"+firstAndSecond[1]);

will give you:

First:15.94, Second:16.01
2015-05-16 00:01
by Mawhrin-Skel
Ads