Padding a String, fill a string with a number of occurrences of some character to a certain width. - C++ STL

C++ examples for STL:string

Description

Padding a String, fill a string with a number of occurrences of some character to a certain width.

Demo Code

#include <string>
#include <iostream>

using namespace std;

// The generic approach
template<typename T>
void pad(basic_string<T>& s, typename basic_string<T>::size_type n, T c) {
   if (n > s.length())
      s.append(n - s.length(), c);//from   w  ww  . j  a  va  2s.com
}

int main() {

   string  s  = "this is a test";
   wstring ws = L"this is another test"; // The "L" indicates that this is a wide char literal
   pad(s, 20, '*');
   pad(ws, 20, L'*');

   wcout << ws << std::endl;
}

Result


Related Tutorials