Search code examples
c++run-length-encoding

Difficulty writing run length encoder in c++


Trying to write this run length encoder, and it basically works but it is not passing test cases because of a '/0'.

Code

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;

Error message:

Expected equality of these values:
  run_length_encode("A")
    Which is: "A\0"
  "A"

Answer should be A but my code returns A\0.


Solution

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

    should be

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

    In C++ string indexes start at zero and finish one before the length of the string.