Replace Substring in a String

Definition & Explanation

Replacing a substring in a string involves finding occurrences of a specific substring within the string and replacing them with another substring. This process is commonly used in text processing and string manipulation tasks. Here’s the concept behind it:

  1. Input String: Accept a string as input.
  2. Substrings: Identify the substring that needs to be replaced and the substring that will replace it.
  3. Search: Search for occurrences of the substring to be replaced within the input string.
  4. Replace: Replace each occurrence of the substring with the replacement substring.
  5. Output: Output the modified string with the replaced substring.

For example, consider the input string “Hello, world!” and we want to replace “world” with “Universe”. The process involves finding the substring “world” in the input string and replacing it with “Universe”, resulting in the modified string “Hello, Universe!”.

Program Logic

  1. Input: Accept the original string, the substring to be replaced (old substring), and the substring that will replace it (new substring) as input.
  2. Find Substring Occurrences: Search for occurrences of the old substring within the original string. Keep track of the starting index of each occurrence.
  3. Replace Substring: For each occurrence found, replace the old substring with the new substring starting from its starting index.
  4. Repeat: Repeat steps 2 and 3 until all occurrences of the old substring have been replaced.
  5. Output: Return the modified string with the replaced substrings.

This logic ensures that all occurrences of the old substring are replaced with the new substring in the original string, resulting in the desired modified string.

C

Method 1 :

#include<stdio.h>  
#include<string.h>  
  int main() {
        char str[256] = "prepinsta", substr[128] = "insta", replace[128] = "ster ", output[256];
        int i = 0, j = 0, flag = 0, start = 0;
        
        str[strlen(str) - 1] = '\0';
        substr[strlen(substr) - 1] = '\0';
        replace[strlen(replace) - 1] =  '\0';

        // check whether the substring to be replaced is present 
        while (str[i] != '\0')
        {
                if (str[i] == substr[j]) 
                {
                        if (!flag)
                                start = i;
                        j++;
                        if (substr[j] == '\0')
                                break;
                        flag = 1;
                } 
                else 
                {
                        flag = start = j = 0;
                }
                i++;
        }
        if (substr[j] == '\0' && flag)
        {
                for (i = 0; i < start; i++)
                        output[i] = str[i];

                // replace substring with another string 
                for (j = 0; j < strlen(replace); j++) 
                {
                        output[i] = replace[j];
                        i++;
                }
                // copy remaining portion of the input string "str" 
                for (j = start + strlen(substr); j < strlen(str); j++)
                {
                        output[i] = str[j];
                        i++;
                }
                // print the final string 
                output[i] = '\0';
                printf("Output: %s\n", output);
        } else {
                printf("%s is not a substring of %s\n", substr, str);
        }
        return 0;
  }

Output :

C++

Method 1 :

#include <iostream>
#include <string>
using namespace std;

void replaceSubstring(string &originalString, const string &oldSubstring, const string &newSubstring) {
    size_t position = originalString.find(oldSubstring);
    if (position != string::npos) {
        originalString.replace(position, oldSubstring.length(), newSubstring);
    }
}

int main() {
    string originalString = "Hello, world! Hello, world!";
    const string oldSubstring = "world";
    const string newSubstring = "Universe";
    replaceSubstring(originalString, oldSubstring, newSubstring);
    cout << "Modified string: " << originalString << endl;
    return 0;
}

Output :

JAVA

Method 1 :

public class SubstringReplacement {
    public static String replaceSubstring(String originalString, String oldSubstring, String newSubstring) {
        return originalString.replace(oldSubstring, newSubstring);
    }

    public static void main(String[] args) {
        String originalString = "Hello, world! Hello, world!";
        String oldSubstring = "world";
        String newSubstring = "Universe";
        String modifiedString = replaceSubstring(originalString, oldSubstring, newSubstring);
        System.out.println("Modified string: " + modifiedString);
    }
}

Output :

Python

Method 1 :

def replace_substring(original_string, old_substring, new_substring):
    return original_string.replace(old_substring, new_substring)

# Test the function
original_string = "Hello, world! Hello, world!"
old_substring = "world"
new_substring = "Universe"
modified_string = replace_substring(original_string, old_substring, new_substring)
print("Modified string:", modified_string)

Output :

Modified string: Hello, Universe! Hello, Universe!