Amit Nandal
Amit Nandal

Reputation: 128

about strings in c++

This is the code for removing consecutive words:

std::string unstretch(std::string word)
{
    std::string s;
    int k=0;

    for(int i=0;i<word.length();k++,i++)
    {
        if(word[i]!=word[i+1])
        {
            s[k]=word[i];
        }
        else
            k--;
    }
    s[k]='\0';
    return s;
}

This code works if we replace string s with char s[50]. Can someone explain why this happens?

Upvotes: 0

Views: 161

Answers (2)

Hemil
Hemil

Reputation: 1036

The problem is you are treating string as a char array. Its not just a char array. So,

  1. You don't need to keep an index to append
  2. You don't need the null terminator

I think what your program does is remove the duplicate characters. This is how you would probably do it:

std::string unstretch(std::string word)
{
    std::string s;

    for(int i=0;i<word.length();i++)
    {
        if(word[i]!=word[i+1])
        {
            s += word[i];
        }
    }
    return s;
}

Upvotes: 0

Jesper Juhl
Jesper Juhl

Reputation: 31488

s is an empty string. You cannot use operator[] on an index that doesn't exist.

Upvotes: 3

Related Questions