C++ std::string::find 总是返回 npos

C++ std::string::find always returns npos?

本文关键字:返回 npos find std string C++      更新时间:2023-10-16

我试图让这个函数切开一个字符串,然后返回它,没有空格和全部小写。为此,我试图找到一个" ",以查看字符串"The Time Traveller (for so it will be convenient to speak of him)"是否包含空格。

代码如下,将上面的字符串传递给此函数。它总是返回string::npos .对这个问题有任何想法吗?

string chopstring(string tocut){
    string totoken = ""; 
    int start = 0;
    while(tocut[0] == ' ' || tocut[0] == 10 || tocut[0 == 13]){
        tocut.erase(0);
    }
    int finish = 0;
    finish = tocut.find(" ", start);
    if (finish == string::npos){
        cout << "NPOS!" << endl;
    }
    for (int i = start; i < finish; i++){
        totoken += tocut[i];
    }
    tocut.erase(start, finish);
    return tokenize(totoken);
}

>tocut.erase(0)正在擦除所有tocut。参数是要擦除的第一个字符,默认长度为"所有内容"。

tocut[0 == 13]可能应该tocut[0] == 13.这些说法大相径庭。另外,请与字符值('t'(而不是整数进行比较。顺便说一下,结合前面的是你的实际问题:tocut[0 == 13]变得tocut[false],这是tocut[0],这是true。所以循环一直运行到tocut为空,这是立即的(因为你在第一次去中过度地擦除了它(。

上述两个 bug 的净效果是,当你到达 find 语句时,tocut 是空字符串,它不包含空格字符。继续前进...

您可以使用 substr 函数而不是循环从 tocut 迁移到 totoken

您的最后一行tocut.erase(start, finish)没有做任何有用的事情,因为tocut是按值传递的,之后您会立即返回。

实际上,大多数代码可以写得更简单(假设我理解您要删除所有空格是正确的(:

string chopstring(string tocut) {
    std::string::size_type first(tocut.find_first_of(" nr"));
    if (first != tocut.npos) {
        tocut.substr(first);
    }
    tocut.erase(std::remove(tocut.begin(), tocut.end(), ' '), tocut.end());
    return tokenize(tocut);
}

如果您实际上要删除所有空格,则可能需要将std::remove_if()与合适的谓词一起使用。