将字符串绑定到输入流istringstream,然后使用getline的第三个参数,自定义使用什么符号进行分割就可以了。

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
void split(const string& s,vector<int>& sv,const char flag = ' ') {
sv.clear();
istringstream iss(s);
string temp; while (getline(iss, temp, flag)) {
sv.push_back(stoi(temp));
}
return;
} int main() {
string s("123:456:7");
vector<int> sv;
split(s, sv, ':');
for (const auto& s : sv) {
cout << s << endl;
}
system("pause");
return ;
}

2、使用strtok函数。

strtok()用来将字符串分割成一个个片段。参数s指向欲分割的字符串,参数delim则为分割字符串中包含的所有字符。当strtok()在参数s的字符串中发现参数delim中包含的分割字符时,则会将该字符改为\0 字符。在第一次调用时,strtok()必需给予参数s字符串,往后的调用则将参数s设置成NULL。每次调用成功则返回指向被分割出片段的指针

#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char sentence[]="This is a sentence with 7 tokens";
cout << "The string to be tokenized is:\n" << sentence << "\n\nThe tokens are:\n\n";
char *tokenPtr=strtok(sentence," ");//sentence必须是一个char数组,不能是定义成指针形式
while(tokenPtr!=NULL) {
cout<<tokenPtr<<'\n';
tokenPtr=strtok(NULL," ");
}
//cout << "After strtok,sentence=" << tokenPtr<<endl;
return ;
} //对于string s;
//char tar[10000];
//strcpy(tar,s.c_str());

最新文章

  1. 好程序员带你了解一下HTTPS和SSL/TLS协议的背景与基础
  2. linux driver编译环境搭建和命令
  3. Struts2学习笔记 - Action篇&lt;配置文件中使用通配符&gt;
  4. linux unzip命令
  5. linux常用命令--ps、netstat、find
  6. linux导入导出数据库方法 windows导入导出数据库方法
  7. IT项目各阶段管理
  8. Jquery 使用Ajax获取后台返回的Json数据后,页面处理
  9. 【Android应用开发】Android Studio 错误集锦 -- 将所有的 AS 错误集合到本文
  10. C++中继承与抽象类
  11. [数据结构] 2.7 Heap 堆
  12. ubuntu 14.04解决wifi连接不稳定问题
  13. 关于scrapy 使用代理相关问题
  14. 【转】Ubuntu做日常开发电脑的系统是一种怎样的体验
  15. suse11 sp4(虚拟机) 能ping通主机,但是主机ping不通suse虚拟机
  16. 2019 rode of my LeetCode
  17. MySQL 5.7.14 win10安装
  18. tornado-About Web
  19. how to disabled iframe page open new window / new tab
  20. 【bzoj3930】 CQOI2015—选数

热门文章

  1. NumPy迭代数组
  2. C# extract img url from web content then download the img
  3. Python之xlrd模块读取xls文件与报错解决
  4. 书写makefile的注意点
  5. SpringBoot之Configuration
  6. 【Unity|C#】基础篇(2)——栈与堆、值类型与引用类型
  7. 51nod(1089 最长回文子串 V2)(hash 加二分)
  8. 关于spring整合前两大框架的一些小问题04
  9. 在bootstrap的column中的formatter里不能传递row参数吗?
  10. jeecgboot数据字典使用