打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
C++字符串分割

文章目录

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
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
C++的输入输出流、文件操作
string和stringstream用法总结
4.3 string类
精选算法题(4)——字符串比较
java.util.StringTokenizer
char转16进制字符串:0x1A-->1A
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服