其他语言的lib中,对于string类都有丰富的操作函数,而C++中却不提供一些特殊的函数功能。通过现有的一些函数也可以在c++中实现trim( )、split()等功能。
trim函数
trim( )的作用:去掉字符串首尾的空格。
可以借助 string类中的find_first_not_of( )、find_last_not_of( )函数进行构造
string trim(const string& str) {
string::size_type pos = str.find_first_not_of(' ');
if (pos == string::npos) { //若找不到空格
return str;
}
string::size_type pos2 = str.find_last_not_of(' ');
if (pos2 != string::npos)
return str.substr(pos, pos2 - pos + 1); //子串:第一个非空格作为起始位置
// 字符个数:pos2-pos+1
return str.substr(pos);
}
split函数
split函数功能:从字符串中按照特定的分隔符进行分割,分割的结果保存到std::vector中。
例:按照分隔符“ ,”进行分割split
int split(const string& str, vector<string>& rect_, string sep = ","){
if (str.empty()) return 0;
string tmp;
string::size_type pos_begin = str.find_first_not_of(sep); //第一个非分隔符的位置
string::size_type comma_pos = 0;
while (pos_begin != string::npos) {
comma_pos = str.find(sep, pos_begin); //从下表pos_begin处开始查找字符“,”,返回其下标
if (comma_pos != string::npos) { //comma_pos :下一个分隔符的位置
tmp = str.substr(pos_begin, comma_pos - pos_begin);
pos_begin = comma_pos + sep.length();
}
else {
tmp = str.substr(pos_begin);
pos_begin = comma_pos;
}
if (!tmp.empty()) {
rect_.push_back(tmp);
tmp.clear;
}
}
return 0;
}