The std::string type of the STL library does not provide common Ltrim/rtrim/trim member functions. The following code implements these functions in the form of external independent functions:
1 namespace {2 BOOLIsntspace (Const Char&ch) {3 return!isspace (CH);4 }5}//End of namespace6 7 Const stringLTrimConst string&s) {8 string:: Const_iterator iter =find_if (S.begin (), S.end (), isntspace);9 return string(ITER, S.end ());Ten } One A Const stringRTrimConst string&s) { - string:: Const_iterator iter = find_if (S.rbegin (), S.rend (), isntspace).Base(); - return string(S.begin (), ITER); the } - - Const stringTrimConst string&s) { - string:: Const_iterator iter1 =find_if (S.begin (), S.end (), isntspace); + string:: Const_iterator iter2 = find_if (S.rbegin (), S.rend (), isntspace).Base(); - + returnIter1 < iter2?string(Iter1, Iter2):string(""); A}
Simply explain the algorithm:
Isntspace is a custom function that is in the anonymous namespace and can only be referenced in the local compilation unit. The function calls the standard library function isspace.
find_if The algorithm iterates over the specified region, returns the first qualified iterator, and returns the range end iterator if it is not found.
Find_if (S.begin (), S.end (), isntspace); The statement traverses S.begin () to S.end (). The function Isntspace examines each character that is traversed, and returns the iterator if it finds that the character is not a space.
Find_if (S.rbegin (), S.rend (), isntspace); The statement traverses S.rbegin () to S.rend (), which is a reverse traversal, which is the traversal from the end of the string. The function Isntspace examines each character that is traversed, and returns the iterator if it finds that the character is not a space.
Base () This function returns the forward iterator corresponding to the reverse iterator.
The string::const_iterator is a random iterator, so the order can be compared by the < operator.
Another common online notation is to use Std::not (ispace) instead of custom function Isntspace. This looks like a "more pure STL", but I personally prefer using a custom function instead of using a composite template.
Realization of std::string LTrim, RTrim and Trim methods