C Online Compiler
Example: Substring Replacement (Same Length) in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Substring Replacement (Same Length) #include <stdio.h> #include <string.h> // For strlen, strstr, strncpy // Function to replace the first occurrence of a substring // Assumes replace_with has the same length as find_str void replace_same_length(char *text, const char *find_str, const char *replace_with) { char *match = strstr(text, find_str); // Step 1: Find the first occurrence of find_str if (match != NULL) { // Step 2: If found // Step 3: Copy replace_with into the location where find_str was found // Use strncpy to prevent buffer overflow if lengths mismatch (though assumed same here) strncpy(match, replace_with, strlen(replace_with)); } } int main() { char buffer[100] = "Hello world, hello C!"; const char *find = "hello"; const char *replace = "greet"; // "greetings" is longer, "greet" is same length as "hello" printf("Original string: %s\n", buffer); replace_same_length(buffer, find, replace); // Step 1: Call the replacement function printf("String after replacement: %s\n", buffer); // Another example char sentence[100] = "The quick brown fox jumps over the lazy dog."; replace_same_length(sentence, "fox", "cat"); printf("Sentence after 'fox' -> 'cat': %s\n", sentence); return 0; }
Output
Clear
ADVERTISEMENTS