4.2. Trimming a String
Problem
You need to trim some number of characters from the end(s) of a string, usually whitespace.
Solution
Use iterators to identify the portion of the string you want to remove, and the
erase member function to remove it. Example 4-2 presents the function rtrim that trims a character from the end of a string.
Example 4-2. Trimming characters from a string
#include <string>
#include <iostream>
// The approach for narrow character strings
void rtrim(std::string& s, char c) {
if (s.empty())
return;
std::string::iterator p;
for (p = s.end(); p != s.begin() && *--p == c;);
if (*p != c)
p++;
s.erase(p, s.end());
}
int main()
{
std::string s = "zoo";
rtrim(s, 'o');
std::cout << s << '\n';
}Discussion
Example 4-2 will do the trick for
strings of chars, but it only
works for char strings. Just like you saw in Example 4-1, you can take advantage of the
generic design of basic_string and use a function
template
instead. Example 4-3 uses a
function template to trim characters from the end of any kind of character string.
Example 4-3. A generic version of rtrim
#include <string> #include <iostream> using namespace std; // The generic approach for trimming single // characters from a string template<typename T> void rtrim(basic_string<T>& s, T c) { if (s.empty()) return; typename basic_string<T>::iterator p; for (p = s.end(); p != s.begin() && *--p == c;); if (*p != c) p++; s.erase(p, s.end()); } int main() { string s = "Great!!!!"; wstring ws = L"Super!!!!"; rtrim(s, '!'); ...