Last active
January 13, 2016 19:57
-
-
Save Youka/b42a9e306649d5470485 to your computer and use it in GitHub Desktop.
C string find&replace
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <string.h> | |
| #include <stdlib.h> | |
| // Replace string in string by creating a new one | |
| char* str_replace(char* original, const char* find, const char* replacement, const char free_original){ | |
| // Initializations | |
| int found_count = 0; | |
| const size_t find_len = strlen(find), replacement_len = strlen(replacement); | |
| char* result, *presult; | |
| const char* poriginal = original, *found; | |
| // Count founds | |
| while(found = strstr(poriginal, find)){ | |
| found_count++; | |
| poriginal = found + find_len; | |
| } | |
| // Allocate memory for output | |
| if(result = malloc(strlen(original) + found_count * (replacement_len - find_len) + 1)){ | |
| // Build output string | |
| presult = result, poriginal = original; | |
| while(found = strstr(poriginal, find)){ | |
| found_count = found - poriginal; | |
| memcpy(presult, poriginal, found_count); | |
| memcpy(presult+found_count, replacement, replacement_len); | |
| presult += found_count + replacement_len; | |
| poriginal = found + find_len; | |
| } | |
| strcpy(presult, poriginal); | |
| } | |
| // Free old string | |
| if(free_original) | |
| free(original); | |
| // Return output | |
| return result; | |
| } | |
| #include <stdio.h> | |
| // Program entry | |
| int main(){ | |
| // Test text replacement | |
| char* output = str_replace("This is a test and he is needed!", " is ", " was ", 0); | |
| puts(output); | |
| free(output); | |
| // Program ends successful | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment