c++ 分割字符串,字符串转数组
2013-02-03 23:08
218 查看
第一种方式strtok
二、用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)
返回值:子字符串
//借助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++ 字符串分割成数组
- c++里面的字符数组和字符串及其分割
- C/C++如何把一个特定分隔符分割的字符串划分为一个字符串数组,strtok(char *,char*)分割函数
- c++ 分割字符串存入数组
- C++组合应用之strtok字符串分割、数组平分算法、动态数组函数传参
- C/C++把字符串划分为二维字数组,2种分割方法
- 函数字符串C++的String类的字符串分割实现----(效果等于Java的String类的split函数)
- CF611D 【分割字符串使得形成的数字数组呈递增状态】的方法数
- C#封送二维字符串数组到C++的示例
- 第一章 1.如何把一段逗号分割的字符串转换成一个数组?
- c++ cin读取字符串数组实现回车结束输入
- (26)'c++:COMPLETE REFERENCE' 第一部分 第四章(数组和以空字符结束的字符串) 第一节
- (29)'c++:COMPLETE REFERENCE' 第一部分 第四章(数组和以空字符结束的字符串) 第四节
- 【旧资料整理】c\c++两种定义字符串数组方法内存开销比较
- 小例子拾掇知识点之c/c++篇第1话--c分割字符串方法
- string 关键字 字符串 分割 组成 list 数组
- C++基础之字符数组和字符串
- 字符串分割到二维字符数组中:
- C++ 分割字符串,可以识别开头的,中间的,末尾的一个或者多个空格
- C# : 字符串分割数组