C++ Split string into vector<string> by space

 

在C++中,我们有时候需要拆分字符串,比如字符串string str = "dog cat cat dog"想以空格区分拆成四个单词,Java中实在太方便了,直接String[] v = str.split(" ");就搞定了,而c++中没有这么方便的实现,但也有很多的方法能实现这个功能,下面列出五种常用的实现的方法,请根据需要选择,个人觉得前三种使用起来比较方便,参见代码如下:

 

    #include <vector>
    #include <iostream>
    #include <string>
    #include <sstream>
    
    string str = "dog cat cat dog";
    istringstream in(str);
    vector<string> v;
    
    // Method 1
    string t;
    while (in >> t) {
        v.push_back(t);
    }

// Method 2 // #include <iterator> copy(istream_iterator<string>(in), istream_iterator<string>(), back_inserter(v));
// Method 3 string t; while (getline(in, t, ' ')) { v.push_back(t); }
// Method 4 string str2 = str; while (str2.find(" ") != string::npos) { int found = str2.find(" "); v.push_back(str2.substr(0, found)); str2 = str2.substr(found + 1); } v.push_back(str2);
// Method 5 // #include <stdio.h> // #include <stdlib.h> // #include <string.h> char *dup = strdup(str.c_str()); char *token = strtok(dup, " "); while (token != NULL) { v.push_back(string(token)); token = strtok(NULL, " "); } free(dup);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值