如何拆分逗号分隔的字符串? [英] How to split a comma-separated string?

查看:66
本文介绍了如何拆分逗号分隔的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a String with an unknown length that looks something like this

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

在逗号处分割此字符串以便每个单词都可以成为 ArrayList 的元素的最佳方法是什么?

What would be the optimal way to divide this string at the commas so each word could become an element of an ArrayList?

例如

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.

推荐答案

你可以这样做:

String str = "...";
List<String> elephantList = Arrays.asList(str.split(","));

基本上是 .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.

但是,您似乎在追求字符串列表而不是数组,因此必须使用 Arrays.asList() 实用程序.就像仅供参考,您也可以这样做:

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.

这篇关于如何拆分逗号分隔的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆