Uses a function template to trim characters from the end of any kind of character string. - C++ STL

C++ examples for STL:string

Description

Uses a function template to trim characters from the end of any kind of character string.

Demo Code

#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;// www. jav a2 s.  c  om

   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 = "this is a test!!!!";
   wstring ws = L"test test test!!!!";

   rtrim(s, '!');
   rtrim(ws, L'!');

   cout << s << '\n';
   wcout << ws << L'\n';
}

Result


Related Tutorials