Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

C Program to Replace a Substring in a String

Last Updated on June 23, 2023 by Prepbytes

Replacing a substring from a string means replacing a specific part of a string with another string. It is a common task in programming and can be useful for various purposes such as data processing, text formatting, and input validation.

There are various methods to replace a substring from a string depending on the programming language and the specific requirements of the task. Most programming languages provide built-in functions or methods to replace substrings. These functions usually take the original string, the substring to be replaced, and the replacement string as parameters.

Approach to Replace a Substring in a String

Here’s an algorithm to replace a substring from a string using C, along with an example code implementation:

Algorithm

  • Step 1: Define the original string, the substring to be replaced, and the replacement string.
  • Step 2: Find the position of the first occurrence of the substring within the original string using the strstr() function.
  • Step 3: If the substring is found, calculate the length of the replacement string.
  • Step 4: Create a new string with a length equal to the original string minus the length of the substring plus the length of the replacement string.
  • Step 5: Copy the characters before the substring from the original string to the new string using strncpy() function.
  • Step 6: Append the replacement string to the new string using strcat() function.
  • Step 7: Move the pointer in the original string to the end of the substring.
  • Step 8: Copy the characters after the substring from the original string to the new string using strcat() function.
  • Step 9: Repeat steps 2 to 8 until all occurrences of the substring have been replaced.
  • Step 10: Null terminate the new string.
  • Step 11: Return the modified string.

Code Implementation

#include <stdio.h>
#include <stdlib.h>
#include<string.h>
void solve()
{
    
    char c[100];
    int i, j, length = 0;


    
    printf("Enter a string : ");
    printf("\n");
    // gets(c);
    scanf("%s", c);

    length = strlen(c);

    for (i = 0; i < length; i++) {
       
        if (c[i] == 'A' || c[i] == 'E' || c[i] == 'I' || c[i] == 'O' || c[i] == 'U' ||
         c[i] == 'a' || c[i] == 'e' || c[i] == 'i' || c[i] == 'o' || c[i] == 'u' ) {
           
            for (j = i; j < length; j++) {
              
                c[j] = c[j + 1];
            }
            i--;
            length--;
        }
        c[length + 1] = '\0';
    }
   printf("After Deletion the string will be  : %s", c);
 
}

int main()
{
    solve();
    return 0;
}

Output

The quick brown cat jumps over the lazy dog.

Conclusion
In conclusion, replacing a substring from a string is a common task in programming, and can be performed using various algorithms and implementations depending on the programming language and specific requirements of the task.

The C programming language provides built-in functions such as strstr(), strncpy(), and strcat() that can be used to replace substrings from strings. By using these functions and some pointer manipulation, a basic algorithm can be implemented to replace all occurrences of a substring from a string.

Frequently Asked Questions

Q1. What is the difference between strncpy() and strcpy()?
Ans. strncpy() copies a specified number of characters from one string to another, while strcpy() copies the entire string. It is generally recommended to use strncpy() when copying strings to ensure that the destination string is not overflowed and to avoid potential security vulnerabilities.

Q2. What is the purpose of the strcat() function?
Ans. The strcat() function is used to concatenate or append one string to the end of another. It takes two arguments: the destination string, and the source string to be appended. The resulting string is the original destination string with the source string appended to the end.

Q3. Can the replaceSubstring() function handle multiple substrings to be replaced at once?
Ans. No, the example code provided replaces only one occurrence of the substring at a time. However, the function can be modified to handle multiple substrings by using a loop to replace each occurrence of the substring one at a time until no more are found.

Q4. What happens if the substring is not found in the original string?
Ans. If the substring is not found in the original string, the replaceSubstring() function simply returns the original string without any modifications.

Q5. Is it necessary to free the memory allocated for the result string in the example code?
Ans. Yes, it is necessary to free the memory allocated for the result string using the free() function to avoid memory leaks. This ensures that the memory used by the program is properly managed and freed when it is no longer needed.

Leave a Reply

Your email address will not be published. Required fields are marked *