我有一些String
个对象需要在不同连续字符的位置拆分成一个子串数组。
我的输入/输出应如下所示:
"AAAA" -> ["AAAA"]
"AAAABBB" -> ["AAAA", "BBB"]
"ABBCCC" -> ["A", "BB", "CCC"]
我希望能够编写一行代码:
String[] charRuns = str.split(regex);
输入str
,输出charRuns
,但regex
的价值应该是多少?
答案 0 :(得分:4)
目前还无法找到使用split
执行此操作的方法,但这里有一个基于Pattern
,Matcher
和迭代的解决方案:
String test = "ABBCCCDDDDE";
// | any character, grouped for back-reference
// | | immediate back-reference
// | | | 0+ repetition, greedy
Pattern p = Pattern.compile("(.)\\1*");
Matcher m = p.matcher(test);
while (m.find()) System.out.println(m.group());
<强>输出强>
A
BB
CCC
DDDD
E
答案 1 :(得分:0)
实际上有一种简单的方法可以完全不使用Java正则表达式,这里是伪代码:
获取字符串的第一个字符,将其存储在变量firstChar中。
count -> 1
startIndex -> 0
create a new arrayList to store the strings.
while(count <= string.length){
newChar -> string.charAt(count)
If(newChar != firstChar){
arrayList.add(string.substring(startIndex, count)
firstChar = newChar
startIndex = count
}
increment count
}
在arrayList中获得数据后,您可以迭代它并创建单独的数组。