[java] 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.

This question is related to java string split

The answer is


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 .


Can try with this worked for me

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

or else

if (sg.endsWith(",")) {
                    sg = sg.substring(0, sg.length() - 1);
                }

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*");

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.


Use this :

        List<String> splitString = (List<String>) Arrays.asList(jobtype.split(","));

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

In Kotlin,

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

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


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 :)


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)


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*");

This is an easy way to split string by comma,

import java.util.*;

public class SeparatedByComma{
public static void main(String []args){
     String listOfStates = "Hasalak, Mahiyanganaya, Dambarawa, Colombo";
     List<String> stateList = Arrays.asList(listOfStates.split("\\,"));
     System.out.println(stateList);
 }
}

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*");

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;

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to split

Parameter "stratify" from method "train_test_split" (scikit Learn) Pandas split DataFrame by column value How to split large text file in windows? Attribute Error: 'list' object has no attribute 'split' Split function in oracle to comma separated values with automatic sequence How would I get everything before a : in a string Python Split String by delimiter position using oracle SQL JavaScript split String with white space Split a String into an array in Swift? Split pandas dataframe in two if it has more than 10 rows