- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- Replace String with another in java.
- How to replace all occurrences of a string with another string in Python?
- Replace one string with another string with Java Regular Expressions
- Replace part of string in MySQL table column?
- Can part of a string be rearranged to form another string in JavaScript
- Replace parts of a string with C# Regex
- Replace all words with another string with Java Regular Expressions
- How to replace total string if partial string matches with another string in R data frame column?
- MySQL query to replace part of string before dot
- Does JavaScript have a method to replace part of a string without creating a new string?
- How to use JavaScript to replace a portion of string with another value?
- How to replace all occurrences of a word in a string with another word in java?
- Program to check we can replace characters to make a string to another string or not in C++
- How can we replace specific part of String and StringBuffer in Java?
- How to replace a part of the string (domain name after @) using MySQL?

Advertisements