java - 无法读取重复字符

标签 java string loops char

我正在编写代码来读取字符串并计算重复组

public int countRepeatedCharacters()
{
    int c = 0;
    for (int i = 1; i < word.length() - 1; i++)
    {
        if (word.charAt(i) == word.charAt(i + 1)) // found a repetition
        {
            if ( word.charAt(i - 1) != word.charAt(i)) {

                c++;

            }
        }
    }     
    return c;
}

如果我尝试输入 aabbcdaaaabb 我应该有 4 组重复小数 啊| BB |啊啊| BB

我知道我没有读取第一组 aa,因为我的索引从 1 开始。我尝试将其修复为读取零,但随后我尝试修复整个循环以处理更改,但我失败了,是吗?关于如何更改索引或循环有什么建议吗?

最佳答案

试试这个代码:

public int countRepeatedCharacters(String word)
{
    int c = 0;
    Character last = null;
    bool counted = false;
    for (int i = 0; i < word.length(); i++)
    {
        if (last != null && last.equals(word.charAt(i))) {  // same as previous characted
            if (!counted) {  // if not counted this character yet, count it
                c++;
                counted = true;
            }
        }
        else {      // new char, so update last and reset counted to false
            last = word.charAt(i);
            counted = false
        }
    }     
    return c;
}

编辑 - 将 aaaa 计为 4,固定为计为 1

关于java - 无法读取重复字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16101695/

相关文章:

java - 为什么在堆中创建字符串对象和字符串文字的串联?

java - While 循环导致 print 语句打印两次

java - org.json JSONObject 在从 Spring Boot Controller 返回时向 JSONObject 添加额外的对象

java - 二元运算符的操作数类型错误 '=='

string - 使用 JMeter 从响应 header 中提取位置

Python 模糊搜索和替换

vba - Excel VBA - 让 VBA 脚本循环遍历行

c - 想要通过遍历结构来减少函数

java - 易于使用的 Web API 即可开始使用

java - 无法抑制 DriverManager 的静态初始化 block