关于c ++中的字符串

问题描述 投票:0回答:2

这是删除连续单词的代码:

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;
}

如果我们将string s替换为char s[50],则此代码有效。有人可以解释为什么会这样吗?

c++ string coding-style
2个回答
3
投票

s是一个空字符串。您不能在不存在的索引上使用operator[]


0
投票

问题是您将字符串视为char数组。它不仅仅是一个char数组。因此,

© www.soinside.com 2019 - 2024. All rights reserved.