
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Replace substring with another substring C++
Here we will see how to replace substring with another substring. It replaces the portion of the string that begins at character pos and spans len characters.
The structure of the replace function is like below:
string& replace (size_t pos, size_t len, const string& str, size_t subpos, size_t sublen);
The parameters are pos: It is an insertion point, str : It is a string object, len : It contains information about number of characters to erase.
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> #include <string> using namespace std; int main () { string base = "this is a test string."; string str2 = "n example"; string str3 = "sample phrase"; string str4 = "useful."; string str = base; str.replace(9,5,str2); str.replace(19,6,str3,7,6); str.replace(8,10,"just a"); str.replace(8,6,"a shorty",7); str.replace(22,1,3,'!'); str.replace(str.begin(),str.end()-3,str3); str.replace(str.begin(),str.begin()+6,"replace"); str.replace(str.begin()+8,str.begin()+14,"is coolness",7); str.replace(str.begin()+12,str.end()-4,4,'o'); str.replace(str.begin()+11,str.end(),str4.begin(),str4.end()); cout << str << '\n'; return 0; }
Output
replace is useful.
- Related Articles
- How can we replace all the occurrences of a substring with another substring within a string in MySQL?
- Replace the Substring for Balanced String in C++
- How to replace substring in MongoDB document?
- Replace All Occurrences of a Python Substring with a New String?
- How to replace substring in string in TypeScript?
- Substring in C#
- Substring in C++
- C# Substring() Method
- Substring with Concatenation of All Words in C++
- Repeated Substring Pattern in C++
- Longest Repeating Substring in C++
- Shortest Majority Substring in C++
- Minimum Window Substring in C++
- Longest Duplicate Substring in C++
- Palindrome Substring Queries in C++

Advertisements