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

本文转自博客园Grandyang的博客,原文链接:C++ Split string into vector by space,如需转载请自行联系原博主。

相关文章
|
27天前
|
存储 C++ 容器
C++入门指南:string类文档详细解析(非常经典,建议收藏)
C++入门指南:string类文档详细解析(非常经典,建议收藏)
34 0
|
27天前
|
存储 C++ 容器
【C++】vector的底层剖析以及模拟实现
【C++】vector的底层剖析以及模拟实现
|
30天前
|
存储 算法 测试技术
C++:Vector的使用
C++:Vector的使用
|
1月前
|
存储 算法 C++
【C/C++ Vector容量调整】理解C++ Vector:Reserve与Resize的区别与应用
【C/C++ Vector容量调整】理解C++ Vector:Reserve与Resize的区别与应用
50 1
|
27天前
|
存储 编译器 C语言
C++_String增删查改模拟实现
C++_String增删查改模拟实现
46 0
|
1天前
|
存储 缓存 编译器
【C++进阶(五)】STL大法--list模拟实现以及list和vector的对比
【C++进阶(五)】STL大法--list模拟实现以及list和vector的对比
|
1天前
|
编译器 C++
【C++进阶(三)】STL大法--vector迭代器失效&深浅拷贝问题剖析
【C++进阶(三)】STL大法--vector迭代器失效&深浅拷贝问题剖析
|
5天前
|
存储 安全 C语言
【C++】string类
【C++】string类
|
存储 编译器 Linux
标准库中的string类(中)+仅仅反转字母+字符串中的第一个唯一字符+字符串相加——“C++”“Leetcode每日一题”
标准库中的string类(中)+仅仅反转字母+字符串中的第一个唯一字符+字符串相加——“C++”“Leetcode每日一题”
|
7天前
|
编译器 C++
标准库中的string类(上)——“C++”
标准库中的string类(上)——“C++”

热门文章

最新文章