如何分割逗号分隔的字符串?

时间:2021-04-24 00:17:15

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?

在逗号处划分字符串的最佳方法是什么,以便每个单词都可以成为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.

10 个解决方案

#1


253  

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.

基本上。split()方法将根据您正在传递的(在本例中)分隔符分割字符串,并返回一个字符串数组。

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:

但是,您似乎需要的是字符串列表,而不是数组,因此必须使用Arrays.asList()实用程序将数组转换为列表。作为一个参考,你也可以这样做:

String str = "...";
ArrayList<String> elephantList = 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.

但是,通常更好的做法是对接口编程,而不是实际的具体实现编程,所以我推荐第一个选项。

#2


129  

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

#3


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,

一个小改进:上面的解决方案不会删除实际字符串中的前导或尾随空格。最好在调用split之前调用trim。取而代之的是,

 String[] animalsArray = animals.split("\\s*,\\s*");

use

使用

 String[] animalsArray = animals.trim().split("\\s*,\\s*");

#4


14  

You can split it and make an array then access like array

你可以将它分割成一个数组然后像数组一样访问它

String names = "prappo,prince,ahsan";
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 .

希望它能对你有所帮助。

#5


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

#6


2  

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

为了完整起见,您可以使用番石榴库: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:

split .split()返回一个可迭代的值,因此如果需要一个列表,请将其封装到上面的List . newarraylist()中。否则只使用可迭代的,例如:

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().

注意trimResults()如何处理所有的修剪需求,而不需要像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.

如果您的项目已经使用番石榴,这应该是您的首选解决方案。有关更多配置选项,请参阅Guava用户指南或javadocs中的Splitter文档。

#7


2  

Can try with this worked for me

可以试试这个对我有用吗?

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

or else

否则

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

#8


0  

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

删除所有空格并创建一个固定大小或不变的列表(参见asList API文档)

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)

也可以使用replaceAll(\ s+", "),但是最大的效率取决于用例。(参见@GurselKoca对在Java中从字符串中删除空格的回答)

#9


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;

#10


-1  

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

有一个名为replaceAll()的函数,它可以用您想要的东西替换所有的白空间。作为一个例子

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

#1


253  

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.

基本上。split()方法将根据您正在传递的(在本例中)分隔符分割字符串,并返回一个字符串数组。

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:

但是,您似乎需要的是字符串列表,而不是数组,因此必须使用Arrays.asList()实用程序将数组转换为列表。作为一个参考,你也可以这样做:

String str = "...";
ArrayList<String> elephantList = 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.

但是,通常更好的做法是对接口编程,而不是实际的具体实现编程,所以我推荐第一个选项。

#2


129  

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

#3


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,

一个小改进:上面的解决方案不会删除实际字符串中的前导或尾随空格。最好在调用split之前调用trim。取而代之的是,

 String[] animalsArray = animals.split("\\s*,\\s*");

use

使用

 String[] animalsArray = animals.trim().split("\\s*,\\s*");

#4


14  

You can split it and make an array then access like array

你可以将它分割成一个数组然后像数组一样访问它

String names = "prappo,prince,ahsan";
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 .

希望它能对你有所帮助。

#5


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

#6


2  

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

为了完整起见,您可以使用番石榴库: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:

split .split()返回一个可迭代的值,因此如果需要一个列表,请将其封装到上面的List . newarraylist()中。否则只使用可迭代的,例如:

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().

注意trimResults()如何处理所有的修剪需求,而不需要像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.

如果您的项目已经使用番石榴,这应该是您的首选解决方案。有关更多配置选项,请参阅Guava用户指南或javadocs中的Splitter文档。

#7


2  

Can try with this worked for me

可以试试这个对我有用吗?

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

or else

否则

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

#8


0  

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

删除所有空格并创建一个固定大小或不变的列表(参见asList API文档)

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)

也可以使用replaceAll(\ s+", "),但是最大的效率取决于用例。(参见@GurselKoca对在Java中从字符串中删除空格的回答)

#9


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;

#10


-1  

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

有一个名为replaceAll()的函数,它可以用您想要的东西替换所有的白空间。作为一个例子

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