使用Java 8,如何获取字符串中连续字符的数量?

huangapple go评论61阅读模式
英文:

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 = &quot;aabbbccddbb&quot;;
int count = 1;
for(int i = 0; i &lt; str.length()-1; i++) {
    if(str.charAt(i) == str.charAt(i+1)) {
        count++;
    } else {
        System.out.print(count+ &quot;&quot;+str.charAt(i));
        count = 1;
    }
}
System.out.print(count+&quot;&quot;+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.

  • (?&lt;=(.)) - 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 \\1to 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 = &quot;aabbbccddbb&quot;;
String result = Arrays.stream(str.split(&quot;(?&lt;=(.))(?!\)&quot;))
        .map(s -&gt; 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 -&gt; (s.length() &gt; 1 ? s.length() : &quot;&quot;)
                        + Character.toString(s.charAt(0)))

huangapple
  • 本文由 发表于 2023年6月8日 22:19:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76432820.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定