我有一个长度未知的字符串,看起来像这样

"dog, cat, bear, elephant, ..., giraffe"

用逗号分隔这个字符串的最佳方法是什么,这样每个单词都可以成为数组列表的一个元素?

例如

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.

当前回答

我能试试这个吗

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

否则

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

其他回答

你可以这样使用:

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

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

此外,你应该包括lib:

import java.util.ArrayList;
import java.util.Arrays; 
import java.util.List;

有一个名为replaceAll()的函数,它可以删除所有空白,将它们替换为您想要的任何内容。举个例子

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

会给你:

First:15.94, Second:16.01

首先,你可以像这样拆分名字

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

String animals_list[] = animals.split(",");

访问您的动物

String animal1 = animals_list[0];
String animal2 = animals_list[1];
String animal3 = animals_list[2];
String animal4 = animals_list[3];

此外,你还需要移除动物名称周围的空格和逗号

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

在Kotlin

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

where stringArray是列表<字符串>和commasString是字符串与逗号和空格

简单而简短的解决方案:-

字符串str="测试1,测试2,测试3"; List<String> elementList = Arrays.asList(str. aslist)replaceAll(“\ \ s * \ \ s * ", ", ") .split (", ")); 输出=["test 1","test 2","test 3"]

它适用于所有情况。

稍后谢谢我:-)