STL的string已给我提供一些常用的算法(find,substr,erase,replace等),但在实现应用中远远不能满足需求,像trim,toupper,tolower这样简单的算法都不提供,我曾偶发现一个开源的C++库中简洁优雅实现了这些算法。
1.trimLeft
while (it != end && std::isspace(*it)) ++it;
return S(it, end);
}
2.trimLeftInPlace
while (it != end && std::isspace(*it)) ++it;
str.erase(str.begin(), it);
return str;
}
3.trimRight
while (pos >= 0 && std::isspace(str[pos])) --pos;
return S(str, 0, pos + 1);
}
4.trimRightInPlace
while (pos >= 0 && std::isspace(str[pos])) --pos;
str.resize(pos + 1);
return str;
}
5.trim
while (first <= last && std::isspace(str[first])) ++first;
while (last >= first && std::isspace(str[last])) --last;
return S(str, first, last - first + 1);
}
6.trimInPlace
while (first <= last && std::isspace(str[first])) ++first;
while (last >= first && std::isspace(str[last])) --last;
str.resize(last + 1);
str.erase(0, first);
return str;
}
7.toUpper
S result;
result.reserve(str.size());
while (it != end) result += std::toupper(*it++);
return result;
}
8.toUpperInPlace
while (it != end) { *it = std::toupper(*it); ++it; }
return str;
}
9.toLower
S result;
result.reserve(str.size());
while (it != end) result += std::tolower(*it++);
return result;
}
10.toLowerInPlace
while (it != end) { *it = std::tolower(*it); ++it; }
return str;
}