使用 C++ 检查空格

checking for spaces with c++

本文关键字:空格 检查 C++ 使用      更新时间:2023-10-16

所以我在网站上寻找有类似问题的人,但没有任何结果,这真的让我感到困惑。

#include <iostream>
#include <string>
using namespace std;
string reverse(string s)
{
    int start = 0;
    for(int i = 0; i < s.length(); i++)
    {
        if(s[i]==' '){
            string new_word = s.substr(start,i);
            cout << new_word << endl;
            start = i+1;
         }   
    }
    return "hi";
}

int main(){
    cout << reverse("Hey there my name is am");
    return 0;
}

当我运行上面的代码花絮时,这就是我得到的输出。

Hey
there my 
my name is
name is am
is am
hi

如您所见,if 条件似乎并没有在每个空格上中断。我也尝试过isspace(s[i]),结果与上面相同。我一生都无法弄清楚为什么在某些空格而不是其他空格上跳过 if 条件。有没有人遇到过类似的问题?

看看 string::substr 的引用。它清楚地指出len需要子字符串中包含的字符数。在您的代码中,您传递的是' '索引,这是完全错误的,因为它与len不对应。与其使用s.substr(start,i),不如简单地使用 s.substr(start,i - start + 1) 。这应该可以解决问题。