Open In App

How to Find and Replace All Occurrences of a Substring in a C++ String?

Last Updated : 05 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ Program to Replace all the occurences Substring in a
// String
#include <iostream>
#include <string>
  
using namespace std;
  
int main()
{
    // Input string
    string input = "Hi, my name is Lokesh "
                   ". Lokesh means King of the World";
  
    // Substring to find
    string replace_word = "Lokesh";
  
    // Replacement string
    string replace_by = "Ram";
  
    // Find the first occurrence of the substring
    size_t pos = input.find(replace_word);
  
    // Iterate through the string and replace all
    // occurrences
    while (pos != string::npos) {
        // Replace the substring with the specified string
        input.replace(pos, replace_word.size(), replace_by);
  
        // Find the next occurrence of the substring
        pos = input.find(replace_word,
                         pos + replace_by.size());
    }
  
    // Print the modified string
    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)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads