標籤:des blog http io os 使用 ar for art
經常碰到字串分割的問題,這裡總結下,也方便我以後使用。
一、用strtok函數進行字串分割
原型: char *strtok(char *str, const char *delim);
功能:分解字串為一組字串。
參數說明:str為要分解的字串,delim為分隔字元字串。
傳回值:從str開頭開始的一個個被分割的串。當沒有被分割的串時則返回NULL。
其它:strtok函數線程不安全,可以使用strtok_r替代。
樣本:
1 //藉助strtok實現split
2 #include <string.h>
3 #include <stdio.h>
4
5 int main()
6 {
7 char s[] = "Golden Global View,disk * desk";
8 const char *d = " ,*";
9 char *p;
10 p = strtok(s,d);
11 while(p)
12 {
13 printf("%s\n",p);
14 p=strtok(NULL,d);
15 }
16
17 return 0;
18 }
運行效果:
二、用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)
傳回值:子字串
實現如下:
1 //字串分割函數
2 std::vector<std::string> split(std::string str,std::string pattern)
3 {
4 std::string::size_type pos;
5 std::vector<std::string> result;
6 str+=pattern;//擴充字元串以方便操作
7 int size=str.size();
8
9 for(int i=0; i<size; i++)
10 {
11 pos=str.find(pattern,i);
12 if(pos<size)
13 {
14 std::string s=str.substr(i,pos-i);
15 result.push_back(s);
16 i=pos+pattern.size()-1;
17 }
18 }
19 return result;
20 }
完整代碼:
View Code
運行效果:
三、用Boost進行字串的分割
用boost庫的Regex實現字串分割
實現如下:
1 std::vector<std::string> split(std::string str,std::string s)
2 {
3 boost::regex reg(s.c_str());
4 std::vector<std::string> vec;
5 boost::sregex_token_iterator it(str.begin(),str.end(),reg,-1);
6 boost::sregex_token_iterator end;
7 while(it!=end)
8 {
9 vec.push_back(*it++);
10 }
11 return vec;
12 }
完整代碼:
1 //本程式實現的是利用Regex對字串實現分割
2 //運行環境 VC6.0 + boost 庫
3 /*
4 File : split2.cpp
5 Author : Mike
6 E-Mail : [email protected]
7 */
8 #include <iostream>
9 #include <cassert>
10 #include <vector>
11 #include <string>
12 #include "boost/regex.hpp"
13
14 std::vector<std::string> split(std::string str,std::string s)
15 {
16 boost::regex reg(s.c_str());
17 std::vector<std::string> vec;
18 boost::sregex_token_iterator it(str.begin(),str.end(),reg,-1);
19 boost::sregex_token_iterator end;
20 while(it!=end)
21 {
22 vec.push_back(*it++);
23 }
24 return vec;
25 }
26 int main()
27 {
28 std::string str,s;
29 str="sss/ddd/ggg/hh";
30 s="/";
31 std::vector<std::string> vec=split(str,s);
32 for(int i=0,size=vec.size();i<size;i++)
33 {
34 std::cout<<vec[i]<<std::endl;
35 }
36 std::cin.get();
37 std::cin.get();
38 return 0;
39 }
運行效果:
補充:
最近發現boost裡面有內建的split的函數,如果用boost的話,還是直接用split的好,這裡就不多說了,代碼如下:
#include <iostream>#include <string>#include <vector>#include <boost/algorithm/string/classification.hpp>#include <boost/algorithm/string/split.hpp> using namespace std; int main(){ string s = "sss/ddd,ggg"; vector<string> vStr; boost::split( vStr, s, boost::is_any_of( ",/" ), boost::token_compress_on ); for( vector<string>::iterator it = vStr.begin(); it != vStr.end(); ++ it ) cout << *it << endl; return 0;}
好,就這些了,希望對你有協助。
C對字串的部分操作