在 C++ 中难以编写 运行 长度编码器

Difficulty writing run length encoder in c++

正在尝试编写此 运行 长度编码器,它基本上可以工作,但由于 '/0' 而未通过测试用例。

代码

std::string run_length_encode(const std::string& str)
{
    std::string encoded = "";
    char prevch;
    char newch;
    int count = 1;
    prevch = str[0];
    for (int i = 0; i <= str.length(); i++)
    {
        newch = str[i];
        if (prevch == newch)
        {
            count++;
        }
        else
        {
            encoded += prevch;
            if (count > 1)
            {
                encoded += std::to_string(count);
            }
            prevch = newch;
            count = 1;
        }
    }
    if (prevch == newch)
    {
        encoded += newch;
        if (count > 1)
        {
            encoded += std::to_string(count);
        }
    }
    return encoded;

错误信息:

Expected equality of these values:
  run_length_encode("A")
    Which is: "A[=12=]"
  "A"

答案应该是 A 但我的代码 returns A[=21=].

for (int i = 0; i <= str.length(); i++)

应该是

for (int i = 0; i < str.length(); i++)

在 C++ 中,字符串索引从零开始到字符串长度前 结束