Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

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, '!'); ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page