![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Replace part of a string with another string in C++
Here we will see how to replace a part of a string by another string in C++. In C++ the replacing is very easy. There is a function called string.replace(). This replace function replaces only the first occurrence of the match. To do it for all we have used loop. This replace function takes the index from where it will replace, it takes the length of the string, and the string which will be placed in the place of matched string.
Input: A string "Hello...Here all Hello will be replaced", and another string to replace "ABCDE" Output: "ABCDE...Here all ABCDE will be replaced"
Algorithm
Step 1: Get the main string, and the string which will be replaced. And the match string Step 2: While the match string is present in the main string: Step 2.1: Replace it with the given string. Step 3: Return the modified string
Example Code
#include<iostream> using namespace std; main() { int index; string my_str = "Hello...Here all Hello will be replaced"; string sub_str = "ABCDE"; cout << "Initial String :" << my_str << endl; //replace all Hello with welcome while((index = my_str.find("Hello")) != string::npos) { //for each location where Hello is found my_str.replace(index, sub_str.length(), sub_str); //remove and replace from that position } cout << "Final String :" << my_str; }
Output
Initial String :Hello...Here all Hello will be replaced Final String :ABCDE...Here all ABCDE will be replaced
Advertisements