在Java中是否有任何内置的方法允许我们将逗号分隔的字符串转换为一些容器(例如数组,列表或向量)?或者我需要为此编写自定义代码吗?
String commaSeparated = "item1 , item2 , item3";
List<String> items = //method that converts above string into list??
在Java中是否有任何内置的方法允许我们将逗号分隔的字符串转换为一些容器(例如数组,列表或向量)?或者我需要为此编写自定义代码吗?
String commaSeparated = "item1 , item2 , item3";
List<String> items = //method that converts above string into list??
当前回答
两个步骤:
String [] = commaSeparated.split项目(“\ \ s * \ \ s *”); List<String> container = Arrays.asList(items);
其他回答
数组。asList返回一个由数组支持的固定大小的List。如果你想要一个普通的可变java.util.ArrayList,你需要这样做:
List<String> list = new ArrayList<String>(Arrays.asList(string.split(" , ")));
或者,用番石榴:
List<String> list = Lists.newArrayList(Splitter.on(" , ").split(string));
使用Splitter可以更灵活地分割字符串,例如,可以跳过结果中的空字符串和修剪结果。它的怪异行为也比String少。拆分以及不需要你通过正则表达式拆分(这只是一个选项)。
在Kotlin中,如果你的字符串列表像这样,你可以使用这行代码将字符串转换为数组列表
var str= "item1, item2, item3, item4"
var itemsList = str.split(", ")
一个使用集合的例子。
import java.util.Collections;
...
String commaSeparated = "item1 , item2 , item3";
ArrayList<String> items = new ArrayList<>();
Collections.addAll(items, commaSeparated.split("\\s*,\\s*"));
...
此方法将字符串转换为一个数组,并接受两个参数:要转换的字符串和分隔字符串中的值的字符。它转换它,然后返回转换后的数组。
private String[] convertStringToArray(String stringIn, String separators){
// separate string into list depending on separators
List<String> tempList = Arrays.asList(stringIn.split(separators));
// create a new pre-populated array based on the size of the list
String[] itemsArray = new String[tempList.size()];
// convert the list to an array
itemsArray = tempList.toArray(itemsArray);
return itemsArray;
}
你可以这样做。
这样就去掉了空白和用逗号分隔的地方,你不需要担心空白。
String myString= "A, B, C, D";
//Remove whitespace and split by comma
List<String> finalString= Arrays.asList(myString.split("\\s*,\\s*"));
System.out.println(finalString);