分享

C++字符串分割

 流楚丶格念 2022-01-14

文章目录

1. 自己实现split()

void split(const char *s, vector<string> &strs, char delim = ' ') {
    if(s == nullptr) {
        return;
    }

    const char *head, *tail;
    head = tail = s;

    while(*head != '\0') {
        while(*head != '\0' && *head == delim) {
            head++;
        }

        tail = head;
        while(*tail != '\0' && *tail != delim) {
            tail++;
        }

        if(head != tail) {
            strs.push_back(string(head, tail));
            head = tail;
        } else {
            break;
        }
    }
}

将字符串s按照delim代表的字符分割,并且放入vector中。

搜索过程中在stackoverflow上,发现了另外两个简单明了的办法。

2. stringstream

int main() {
    string str= "I love world!";
    string str_temp;
    stringstream ss;
    str>>ss;
    while(!ss.eof())
    {
    ss>>str_temp;
    cout<<str_temp<<endl;
}
}

这个方法的局限性就是没法使用空格以外的字符进行分割字符串

3.istringstream

istringstream str(" this is a sentence");
string out;

while (str >> out) {
cout << out << endl;
}

运行

 this 
 is 
 a 
 sentence

4. getline() 实现 split()

void split(const std::string &s, std::vector<std::string> &elems, char delim = ' ') {
    std::stringstream ss;
    ss.str(s);
    std::string item;
    while (std::getline(ss, item, delim)) {
        elems.push_back(item);
    }
}

int main()
{
    string line = "asd fasdf fadf fa";
    vector<string> strs;
    split(line, strs);
    for(auto &s: strs) {
        cout << s << endl;
    }
    return 0;
}

getline函数,顾名思义,是用来获取一行数据的,不过它的第三个参数也可以修改成其他字符,这样就可以将其他字符作为行分割符使用。

不过这种实现的缺点就是,getline每遇到一个行分割符都会返回一次,所以对于分割符连续的情况就束手无策了。

例如:

string str= "dsadsad sdsadasd wwwww eeeee";

打印结果就是:

dsadsad 
sdsadasd 
wwwww 
eeeee

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多