C++ 分割字符串的函数

标签 c++

我最近开始使用《Accelerated C++》一书学习 C++。本书介绍了以下函数,用于根据空白字符将字符串拆分为子字符串

vector<string> split(const string& s)
{
    vector<string> ret;
    typedef string::size_type string_size;
    string_size i = 0;

    while (i != s.size()) {
        // ignore leading blanks
        // invariant: characters in range[original i, current i) are all spaces
        while (i != s.size() && isspace(s[i]))
            ++i;

        // find the end of next word
        string_size j = i;
        // invariant: none of the characters in range [original j, current j) is a space
        while (j != s.size() && !isspace(s[j]))
            j++;

        if (i != j) {
            // copy from s starting at i and taking j-i chars
            ret.push_back(s.substr(i, j - i));
            i = j;
        }
    }
    return ret;
}

我的目标是使用这个函数根据逗号分割字符串。所以我将 !isspace(s[j]) 部分更改为 s[j] != ',' 以便该函数使用逗号来识别单词的结尾。我尝试测试该功能如下:

int main() {

    string test_string = "this is ,a test ";

    vector<string> test = split(test_string);

    for (vector<string>::const_iterator it = test.begin(); it != test.end(); ++it)
        cout << *it << endl;

    return 0;
}

当我在终端中编译该函数时,如下所示

g++ -o test_split_function test_split_function.cpp

我没有收到任何错误。但是,当我运行该脚本时,它会继续运行并且不会在命令行中产生任何输出。我不明白为什么,因为根据空格将字符串拆分为单词的函数确实在同一个字符串上运行。

问题:我做错了什么? s[j] != ',' 语句是否不正确?

最佳答案

有两部分需要替换 isspace() 函数,其中一个用于 i 循环:

while (i != s.size() && s[i]==',')
   ++i;

一个用于j循环:

while (j != s.size() && s[j]!=',')
   j++;

这会起作用。

关于C++ 分割字符串的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61159439/

相关文章:

c++ - A* bug(A星搜索算法)

c++ - DBGHelp.dll 导致在调试版本中加载 msvcrt.dll

c++ - 在给定时间内将频率从f1缓慢升高到f2的正弦波

java - 为什么要在 OOPS 中定义重载方法?

C++ double 到二进制表示(重新解释转换)

c++ - 处理浮点不准确的策略

c++ - openCv 裁剪图像

c++ - 声明/定义顺序依赖

c++ - Open GL 在 Codelite Windows 7 上编译,但没有显示输出

c++ - MSVS 2010 和 C++ 标准的构建问题