c++string字符串切割的⽅法
字符串切割的使⽤频率还是挺⾼的,string本⾝没有提供切割的⽅法,但可以使⽤stl提供的封装进⾏实现或者通过c函数strtok()函数实现。
1.通过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 len = npos ) const;
功能:获得⼦字符串。
参数说明:pos为起始位置(默认为0),len为字符串长度(默认为npos)
返回值:⼦字符串
代码如下:
std::vector<std::string>splitWithStl(const std::string &str,const std::string &pattern)
{
std::vector<std::string> resVec;
if(""== str)
{
return resVec;
}
/
/⽅便截取最后⼀段数据
std::string strs = str + pattern;
size_t pos = strs.find(pattern);
size_t size = strs.size();
while(pos != std::string::npos)
{
std::string x = strs.substr(0,pos);
resVec.push_back(x);
strs = strs.substr(pos + pattern.size(), size);
pos = strs.find(pattern);
}
return resVec;
}
2、通过使⽤strtok()函数实现
原型:char *strtok(char *str, const char *delim);
功能:分解字符串为⼀组字符串。s为要分解的字符串,delim为分隔符字符串。
描述:strtok()⽤来将字符串分割成⼀个个⽚段。参数s指向欲分割的字符串,参数delim则为分割字符串,当strtok()在参数s的字符串中发现到参数delim的分割字符时 则会将该字符改为\0 字符。在第⼀次调⽤时,strtok()必需给予参数s字符串,往后的调⽤则将参数s设置成NULL。每次调⽤成功则返回被分割出⽚段的指针。
其它:strtok函数线程不安全,可以使⽤strtok_r替代。
代码如下:
std::vector<std::string>split(const std::string &str,const std::string &pattern) {
/
/const char* convert to char*
c++中string的用法char* strc =new char[strlen(str.c_str())+1];
strcpy(strc, str.c_str());
std::vector<std::string> resultVec;
char* tmpStr =strtok(strc, pattern.c_str());
while(tmpStr !=NULL)
{
resultVec.push_back(std::string(tmpStr));
tmpStr =strtok(NULL, pattern.c_str());
}
delete[] strc;
return resultVec;
};