C++ string replace()

Description

C++ string replace()

#include <iostream>
#include <string>
using namespace std;
int main()//  w ww .  j a va  2 s  . 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;
}
#include <iostream>
#include <string>
using namespace std;
int main()/*from  w w w  .  j ava 2  s.  co m*/
{
   string s1("Quick! from book 2s.com.");
   string s2("Lord test ");
   string s3("Don't test");
   s1.erase(0, 7);
   s1.replace(9, 5, s2);
   s1.replace(0, 1, "s");
   s1.insert(0, s3);
   s1.erase(s1.size()-1, 1);
   s1.append(3, '!');
   int x = s1.find(' ');         //find a space
   while( x < s1.size() )        //loop while spaces remain
   {
      s1.replace(x, 1, "/");     //replace with slash
      x = s1.find(' ');          //find next space
   }
   cout << "s1: " << s1 << endl;
   return 0;
}



PreviousNext

Related