How to Find and Replace All Occurrences of a Substring in a C++ String?
Last Updated :
05 Feb, 2024
In C++, strings are sequences of characters that are used to represent textual data. In this article, we will learn how to find and replace all the occurrences of a particular substring in the given string.
For Example,
Input:
str = "Lokesh is a good programmer, but Lokesh is still in the learning phase."
// replaceing 'Lokesh" with "Ram"
Output:
str = "Ram is a good programmer, but Ram is still in the learning phase."
Find and Replace All Occurrences of a Substring in C++
We will divide the process into two parts: first is finding and then replacing.
- We will use the std::string::find() to find the position of occurrence of the substring in the main string.
- We will then use the std::string::replace() to replace that part of the string and set the range of find() function after the replaced characters to the end of the main string.
- We will keep doing that till the find() function returns the std::string::npos which means that no occurrence is found in the given range.
C++ Program to Replace All the Occurrence of a Substring
C++
#include <iostream>
#include <string>
using namespace std;
int main()
{
string input = "Hi, my name is Lokesh "
". Lokesh means King of the World" ;
string replace_word = "Lokesh" ;
string replace_by = "Ram" ;
size_t pos = input.find(replace_word);
while (pos != string::npos) {
input.replace(pos, replace_word.size(), replace_by);
pos = input.find(replace_word,
pos + replace_by.size());
}
cout << "New String is: " << input << endl;
return 0;
}
|
Output
New String is: Hi, my name is Ram . Ram means King of the World
Time Complexity: O(N*M), where N is the length of the string and M is the length of the substring.
Space Complexity: O(1)
Share your thoughts in the comments
Please Login to comment...