Trimming a String, use iterators to identify the portion of the string, and use the erase member function to remove it. - C++ STL

C++ examples for STL:string

Description

Trimming a String, use iterators to identify the portion of the string, and use the erase member function to remove it.

Demo Code

#include <string>
#include <iostream>

// The approach for narrow character strings
void rtrim(std::string& s, char c) {

   if (s.empty())
      return;/*  ww  w. j  av  a  2 s.  c om*/

   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';
}

Result


Related Tutorials