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

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

问题描述

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

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() 实用程序。就像一个FYI,你也可以这样做:

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 = (ArrayList<String>)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天全站免登陆