C Online Compiler
Example: Substring Replacement (Different Lengths) in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Substring Replacement (Different Lengths) #include <stdio.h> #include <stdlib.h> // For malloc, free #include <string.h> // For strlen, strstr, memcpy, strcpy // Function to replace all occurrences of a substring char* replace_substring(const char *original, const char *find, const char *replace) { char *result; char *ins; // Pointer to current insertion point in `result` char *tmp; // Current search position in `original` int len_find = strlen(find); int len_replace = strlen(replace); int len_original = strlen(original); int count; // Number of matches int new_len = 0; // Step 1: Count occurrences of 'find' to calculate the new total length for (count = 0, ins = (char*)original; (tmp = strstr(ins, find)) != NULL; count++) { ins = tmp + len_find; } // Step 2: Calculate the new string length new_len = len_original + (len_replace - len_find) * count; // Step 3: Allocate memory for the new string (+1 for null terminator) result = (char*)malloc(new_len + 1); if (!result) return NULL; // Handle allocation failure // Step 4: Construct the new string ins = result; tmp = (char*)original; while (count--) { // Loop through each match char *match = strstr(tmp, find); // Find the next match int len_prefix = match - tmp; // Length of the segment before the match // Copy prefix memcpy(ins, tmp, len_prefix); ins += len_prefix; // Copy replacement string memcpy(ins, replace, len_replace); ins += len_replace; // Move `tmp` past the current `find` occurrence tmp = match + len_find; } // Step 5: Copy the remaining part of the original string strcpy(ins, tmp); return result; // Return the newly allocated string } int main() { const char *str = "Hello world, hello C! This is a hello world example."; const char *find = "hello"; const char *replace = "greetings"; // Longer replacement printf("Original string: %s\n", str); char *new_str = replace_substring(str, find, replace); // Step 1: Call replacement function if (new_str) { printf("String after replacement: %s\n", new_str); free(new_str); // Step 2: Free the dynamically allocated memory } else { printf("Memory allocation failed or no replacements made.\n"); } const char *str2 = "aaabbbaaa"; const char *find2 = "bbb"; const char *replace2 = "c"; // Shorter replacement printf("Original string 2: %s\n", str2); char *new_str2 = replace_substring(str2, find2, replace2); if (new_str2) { printf("String 2 after replacement: %s\n", new_str2); free(new_str2); } return 0; }
Output
Clear
ADVERTISEMENTS