我有一个长度未知的字符串,看起来像这样
"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.
“老式”(JDK1.0) java。StringTokenizer类:
StringTokenizer(String str, String delim)
import java.util.*;
public class Tokenizer {
public static void main(String[] args) {
String str = "dog, cat, bear, elephant, ..., giraffe";
StringTokenizer tokenizer = new StringTokenizer(str, ",");
List<String> strings = new ArrayList<String>();
while (tokenizer.hasMoreTokens()) {
// if need to trim spaces .trim() or use delim like ", "
String token = tokenizer.nextToken().trim();
strings.add(token);
}
// test output
strings.forEach(System.out::println);
}
}
注:
StringTokenizer是出于兼容性考虑而保留的遗留类,尽管不鼓励在新代码中使用它。建议寻求此功能的人使用String的split方法或java.util.regex包。
例子:
import java.util.regex.*;
...
// Recommended method<?>
Pattern commaPattern = Pattern.compile("\\s*,\\s*");
String[] words = commaPattern.split(str);
List<String> wordList = new ArrayList<String>(Arrays.asList(words));
// test output
wordList.forEach(System.out::println);
...
首先,你可以像这样拆分名字
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*");
在构建。gradle加番石榴
compile group: 'com.google.guava', name: 'guava', version: '27.0-jre'
然后
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);
}
享受:)