1. 程式人生 > >C++常用字符串分割

C++常用字符串分割

出現 sub e-mail 總結 string類 lease -s del 函數

C++常用字符串分割方法實例匯總,包括了strtok函數、STL、Boost等常用的各類字符串分割方法,非常具有實用價值,需要的朋友可以參考下
本文實例匯總了C++常用字符串分割方法,分享給大家供大家參考。具體分析如下:
我們在編程的時候經常會碰到字符串分割的問題,這裏總結下,也方便我們以後查詢使用。
一、用strtok函數進行字符串分割
原型: char *strtok(char *str, const char *delim);
功能:分解字符串為一組字符串。
參數說明:str為要分解的字符串,delim為分隔符字符串。
返回值:從str開頭開始的一個個被分割的串。當沒有被分割的串時則返回NULL。
其它:strtok函數線程不安全,可以使用strtok_r替代。
示例:
//借助strtok實現split
#include <string.h>
#include <stdio.h>

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

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)
返回值:子字符串
實現如下:
//字符串分割函數
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;
}

完整代碼:
/*
File : split1.cpp
Author : Mike
E-Mail : [email protected]
*/
#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++常用字符串分割