英文:
Using Java 8 how can I get count of consecutive characters in a string
问题
使用Java 8,如何在字符串中获得连续字符的计数。
String str = "aabbbccddbb";
// 输出: 2a3b2c2d2b
请注意b的计数不是5
// 我能用这个实现。但我们如何在Java 8中实现它
String str = "aabbbccddbb";
int count = 1;
for(int i = 0; i < str.length()-1; i++) {
if(str.charAt(i) == str.charAt(i+1)) {
count++;
} else {
System.out.print(count+ "" +str.charAt(i));
count = 1;
}
}
System.out.print(count+""+str.charAt(str.length()-1));
英文:
Using Java 8 how can I get count of consecutive characters in a string. like
String str = "aabbbccddbb";
// output: 2a3b2c2d2b
Please note that count of b is not 5
// I was able to do it with this. But how can we achieve it using Java 8
String str = "aabbbccddbb";
int count = 1;
for(int i = 0; i < str.length()-1; i++) {
if(str.charAt(i) == str.charAt(i+1)) {
count++;
} else {
System.out.print(count+ ""+str.charAt(i));
count = 1;
}
}
System.out.print(count+""+str.charAt(str.length()-1));
答案1
得分: 1
为了实现您的最终目标,您不必计算字符数。您可以在不同相邻字符之间拆分,然后使用每个子字符串的长度。
(?<=(.))
- 一个零宽度的正向回顾后断言,捕获在捕获组中的字符。(?!\\1)
- 然后是任何负零宽度的正向前瞻,用于不同于刚刚捕获的字符的字符(使用回溯引用\\1
到捕获组一)。- 然后将每个子字符串映射到其长度,后跟字符串的第一个字符。
- 并使用收集器连接每个子结果。
String str = "aabbbccddbb";
String result = Arrays.stream(str.split("(?<=(.))(?!\)"))
.map(s -> s.length() + Character.toString(s.charAt(0)))
.collect(Collectors.joining());
System.out.println(result);
输出
2a3b2c2d2b
如果您不想为单个字符的子字符串添加数字,您可以将映射更改为以下内容:
.map(s -> (s.length() > 1 ? s.length() : "") + Character.toString(s.charAt(0)))
英文:
To achieve your ultimate goal, you don't have to count the characters. You can split between different adjacent characters and then use the length of each substring.
(?<=(.))
- a zero width look behind for a character, captured in the capture group.(?!\\1)
- followed by any negative zero-width look ahead for a different character from the one just captured (using a back reference\\1
to capture group one).- then map each sub-string to its length followed by the first character of the string.
- and join each sub-result with a collector.
String str = "aabbbccddbb";
String result = Arrays.stream(str.split("(?<=(.))(?!\)"))
.map(s -> s.length() + Character.toString(s.charAt(0)))
.collect(Collectors.joining());
System.out.println(result);
prints
2a3b2c2d2b
If you don't want a number for single character sub-strings, you can change the map to this:
.map(s -> (s.length() > 1 ? s.length() : "")
+ Character.toString(s.charAt(0)))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论