c++ 分割字符串,字符串转数组
来源:互联网 发布:淘宝种子新规 编辑:程序博客网 时间:2024/06/17 15:10
第一种方式strtok
//借助strtok实现split #include <string.h> #include <stdio.h>#include <iostream>using namespace std; int main() { char s[] = "Golden Global View,disk * desk"; const char *d = " ,*"; char *p; p = strtok(s,d); while(p) { printf("%s\n",p); p=strtok(NULL,d); } //while(_getch()!=27) int wait; cin>>wait; return 0; }
二、用STL进行字符串的分割
涉及到string类的两个函数find和substr:
1、find函数
原型:size_t find ( const string& str, size_t pos = 0 ) const;
功能:查找子字符串第一次出现的位置。
参数说明:str为子字符串,pos为初始查找位置。
返回值:找到的话返回第一次出现的位置,否则返回string::npos
2、substr函数
原型:string substr ( size_t pos = 0, size_t n = npos ) const;
功能:获得子字符串。
参数说明:pos为起始位置(默认为0),n为结束位置(默认为npos)
返回值:子字符串
#include <iostream> #include <string> #include <vector> //字符串分割函数 std::vector<std::string> split(std::string str,std::string pattern) { std::string::size_type pos; std::vector<std::string> result; str+=pattern;//扩展字符串以方便操作 int size=str.size(); for(int i=0; i<size; i++) { pos=str.find(pattern,i); if(pos<size) { std::string s=str.substr(i,pos-i); result.push_back(s); i=pos+pattern.size()-1; } } return result; } int main() { std::string str; std::cout<<"Please input str:"<<std::endl; //std::cin>>str; getline(std::cin,str); std::string pattern; std::cout<<"Please input pattern:"<<std::endl; //std::cin>>pattern; getline(std::cin,pattern);//用于获取含空格的字符串 std::vector<std::string> result=split(str,pattern); std::cout<<"The result:"<<std::endl; for(int i=0; i<result.size(); i++) { std::cout<<result[i]<<std::endl; } std::cin.get(); std::cin.get(); return 0; }
- c++ 分割字符串,字符串转数组
- VB分割字符串为数组 字符串转数组
- C 字符串转数字
- 字符串转数组
- Oracle 字符串转数组
- python 字符串转数组
- php字符串转数组
- 字符串转数组
- 字符串转数组
- json字符串转数组
- String字符串转数组
- JSON字符串转数组
- 字符串转数组 C++
- 字符串转数组
- 字符串转数组
- 字符串转数组
- 字符串转数组
- javascript字符串转数组
- LCD常见接口类型
- iBATIS测试类的详细写法
- 设置MYSQL数据库编码为UTF-8:
- iBATIS中的单元测试
- [cocos2d-x]例如C++的成员函数指针实现委托、监听者模式
- c++ 分割字符串,字符串转数组
- 盘点那些牛人是如何使用笔记本的,现在笔记本真是贱如白菜啊
- 明天看stringstream主要是相当与sprintf/sscanf函数的作用
- PHP扩展开发-06-变量的定义和使用
- js时间比较
- 张孝祥老师银行业务调度系统统视频学习
- JAVA设计模式学习总结
- Java 高质量编程建议(笔记7)
- 在源文件中搜收特定函数在哪个文件中被定义及被哪些文件调用