繁体   English   中英

C++ function 拆分字符串

[英]C++ function to split strings

我最近开始使用 Accelerated C++ 一书开始学习 C++。 本书介绍了以下 function 将字符串拆分为基于空格字符的子字符串

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

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

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

当我在终端中编译 function 时,如下所示

g++ -o test_split_function test_split_function.cpp

我没有错误。 但是,当我运行脚本时,它会继续运行并且不会在我的命令行中生成任何 output。 我不明白为什么,因为基于空格将字符串拆分为单词的 function 确实在同一个字符串上运行。

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

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

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

一个用于j循环:

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

这将起作用。

我对此代码进行了一些更改。 将 ispace function 替换为s[j]==','s[j],=','
检查出来

 #include<bits/stdc++.h>
 using namespace std;

 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() && s[i]==',')
        ++i;

    // find the end of next word
    string_size j = i;
    // here i changed isspace with s[j]!=','
    while (j != s.size() && 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;
 }

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM