C++ tutorial-replace() function


C++ String Manipulation

C++ replace() function

You can use the replace() function to replace a substring by a new string in an invoking string. The replace() function has two forms. The first form can be used to replace a substring(starting from start argument and expanding for num_chars argument) in the invoking string by the entire content of the new string. The second form only takes a proportion of the new string content to replace the substring.

replace(start,num_chars,new_string);

replace(start, num_chars, new_string, start_in_new_string, num_chars);

Example:

#include <cstdlib>
#include <iostream>
#include <conio.h>


using namespace std;


void strmanip(){

  string str="C++ code";
  str.replace(4,4,"Programming");//replace "code" with "Programming"
  cout<<str<<endl;
  str.replace(0,3,"C Programming",0,1);//replace "C++" with "C"
  cout<<str<<endl;

}

int main(){

  strmanip();
  getch();
  return 0;

}


Comments




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.