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

"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.

当前回答

一个小小的改进:上述解决方案不会删除实际字符串中的前导或尾随空格。在调用split之前最好调用trim。 与此相反,

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

use

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

其他回答

我能试试这个吗

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

否则

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

在Kotlin

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

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

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

String names = "prappo,prince";
String[] namesList = names.split(",");

您可以通过它的索引访问它

String name1 = namesList [0];
String name2 = namesList [1];

或者使用循环

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

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

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

一个小小的改进:上述解决方案不会删除实际字符串中的前导或尾随空格。在调用split之前最好调用trim。 与此相反,

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

use

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