如何分离字符串java的特定元素 [英] How to separate specific elements in string java
本文介绍了如何分离字符串java的特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么,我想要做的例子:结果
作为第一个参数和|
作为第二个参数的方法返回|如果在XYZ ABC通
列表(ABC,XYZ)
公开名单<串GT; splitIt(串串,字符串分隔符){
//创建和init数组列表。
清单<串GT;名单=新的ArrayList<串GT;();
//创建和init newString。
串newString =;
//添加字符串ArrayList的名单。
list.add(字符串);
//通过字符串循环。
的for(int i = 0; I< string.length减();我++){
//商店从newString字符串的每个字符。
newString + = string.charAt(ⅰ);
}
newString.replace(分隔符,);
//删除ArrayList的名单字符串。
list.remove(字符串);
//添加newString到ArrayList的名单。
list.add(newString);
返回列表;
}
解决方案
尝试使用拆分
方法:
返回Arrays.asList(string.split(\\\\ |));
这两个反斜线那里,因为拆分
接受正则表达式和 |
是特殊字符的正则表达式。此外,反斜线在Java字符串特殊字符。所以第一个反斜杠转义第二个,其中脱 |
Arrays.asList
将拆分
返回到列表中的数组转换。
Example of what I want to do:
If you pass in "abc|xyz"
as the first argument and "|"
as the second argument the method returns List("abc","xyz")
public List<String> splitIt(String string, String delimiter){
//create and init arraylist.
List<String> list = new ArrayList<String>();
//create and init newString.
String newString="";
//add string to arraylist 'list'.
list.add(string);
//loops through string.
for(int i=0;i<string.length();i++){
//stores each character from string in newString.
newString += string.charAt(i);
}
newString.replace(delimiter, "");
//remove string from arraylist 'list'.
list.remove(string);
//add newString to arraylist 'list'.
list.add(newString);
return list;
}
解决方案
Try using the split
method:
return Arrays.asList(string.split("\\|"));
The two backslashes are there because split
accepts a regex, and |
is a special character in regexes. Also, backslash is a special character in Java strings. So the first backslash escapes the second one, which escapes the |
.
Arrays.asList
will convert the array returned by split
to a list.
这篇关于如何分离字符串java的特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文