Insert, replace and append characters to string - C++ STL

C++ examples for STL:string

Description

Insert, replace and append characters to string

Demo Code

#include <iostream>
#include <string>
using namespace std;
int main()/* ww w  .ja  v  a  2s .  c  o m*/
{
   string str = "this is a test";
   cout << "The original string is: " << str << endl << "  and has " << int(str.length()) << " characters." << endl;
   // Insert characters
   str.insert(4," I am ");
   cout << "The string, after insertion, is: " << str << endl << "  and has " << int(str.length()) << " characters." << endl;
   // Replace characters
   str.replace(12, 6, "to");
   cout << "The string, after replacement, is: " << str << endl << "  and has " << int(str.length()) << " characters." << endl;
   // Append characters
   str = str + " correct";
   cout << "The string, after appending, is: " << str << endl << "  and has " << int(str.length()) << " characters." << endl;
   return 0;
}

Result


Related Tutorials