c++ - 用c++检查空格

标签 c++ string stl

所以我在网站上四处寻找有类似问题的人,但什么也没有出现,这真的让我很困惑。

#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)。这应该可以解决问题。

关于c++ - 用c++检查空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46693707/

相关文章:

c++ - 非常基本的 : Why won't my makefile work with common suffix

c++ - 将值添加到 std::multimap

java - 如何检测字符串是否包含任何从右到左的字符?

c++ - 为 STL 兼容序列容器的实现命名一个好的指南)

c++ - 关于STL数据结构的建议

C++ STL,没有返回类型的函数

c++ - 什么时候需要在 C++ 中使用 malloc?

c++ - 我的插入方法和binsearch方法有问题吗?

java - 按照模板将 long 转换为字符串

c - 如何提取字符串数组的最后3位并将其存储到C中的不同int数组中