Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a comma-separated string?

Tags:

java

string

split

People also ask

How do you split comma separated values in an array?

Use the String. split() method to convert a comma separated string to an array, e.g. const arr = str. split(',') . The split() method will split the string on each occurrence of a comma and will return an array containing the results.

How split comma separated values in SQL query into columns?

Lets split the comma separated phone number list into columns, For this we will use Cross Apply operator, String_Split function and SQL pivot. Following query is used for splitting a comma separated phone number list into columns.


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.


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

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 .


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