Linux C++字符串分割
1. 使用 boost::split() 进行字符串分割
1.1. boost::split() 实例
std::vector<std::string> vStr;
boost::split( vStr, fileName, boost::is_any_of( "-." ), boost::token_compress_on );
for( std::vector<std::string>::iterator it = vStr.begin(); it != vStr.end(); ++ it )
{
std::cout << *it << std::endl;
}
1.2. 根据一个字符进行切割
#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>
using namespace std;
int main()
{
string test = "i am a student,you are a teacher!";
vector<string> vec;
boost::split(vec, test,boost::is_any_of(","), boost::token_compress_on);
for(int i = 0; i < vec.size(); ++i)
{
cout<<vec[i]<<endl;
}
return 0;
}
会根据字符将字符串进行切割
结果:
```
[root@localhost6 tmp]# ./test
i am a student
you are a teacher!
```
1.3. 根据多个字符进行切割
#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>
using namespace std;
int main()
{
string test = "i am a student,you are a teacher!";
vector<string> vec;
boost::split(vec, test,boost::is_any_of(" ,"), boost::token_compress_on);
for(int i = 0; i < vec.size(); ++i)
{
cout<<vec[i]<<endl;
}
return 0;
}
会根据空格与引号将字符串进行切割,每遇到一次切割一次。
结果:
[root@localhost6 tmp]# ./test
i
am
a
student
you
are
a
teacher!
1.4. 根据字符串(也就是根据多个字符)
#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>
using namespace std;
int main()
{
string test = "i am a student<>you are a teacher!";
vector<string> vec;
boost::split(vec, test,boost::is_any_of("<>"), boost::token_compress_on);
for(int i = 0; i < vec.size(); ++i)
{
cout<<vec[i]<<endl;
}
return 0;
}
根据<>进行切割,对于确定字符串中没有<或者>可以使用,否则会根据<,>进行切割。
结果:
[root@localhost6 tmp]# ./test
i am a student
you are a teacher!
2. 使用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;
}
3. 利用 find_first_not_of, find_first_of 实现字符串分割
inline void split(const std::string &s, std::vector<std::string> &tokens, const std::string &delimiters = " ")
{
std::string::size_type lastPos = s.find_first_not_of(delimiters, 0);
std::string::size_type pos = s.find_first_of(delimiters, lastPos);
while (std::string::npos != pos || std::string::npos != lastPos)
{
tokens.push_back(s.substr(lastPos, pos - lastPos).c_str());
lastPos = s.find_first_not_of(delimiters, pos);
pos = s.find_first_of(delimiters, lastPos);
}
}