ReplaceString.c
A function to replace any string (needle) with a string (replacement) within a string (haystack), with the C programming language.
This is really my first attempt at a major C function, so there is doubtless room for improvement. It seems pretty fast in my benchmarks, though.
/* Compile: gcc -ansi -pedantic -O2 ReplaceString.c -o ReplaceString Run: ./ReplaceString */ #include <stdlib.h> #include <string.h> #include <stdio.h> #ifndef uint #define uint unsigned int #endif /* ReplaceString() Replaces needle with replace within haystack (note replacing a char with a char can be done much more efficiently) */ char *ReplaceString(char *needle, char *replace, char *haystack) { char *newString; uint lNeedle = 0; uint lReplace = strlen(replace); uint lHaystack; uint i; uint j = 0; uint k = 0; uint lNew = 0; char active = 0; uint start = 0; uint end = 0; /* Calculate new string size */ for (i = 0; haystack[i] != '\0'; i++) { if ( (!active) && (haystack[i] == needle[0])) { /* Start of needle found */ active = 1; start = i; end = i; } else if ( (active) && (needle[i-start] == 0) ) { /* End of needle */ active = 0; lNew += lReplace - (i-start); lNeedle = (i-start); } else if ( (active) && (needle[i-start] != 0) && (haystack[i] == needle[i-start]) ) { /* Next part of needle found */ end++; } else if (active) { /* Didn't match the entire needle... */ active = 0; } } lHaystack = i; lNew += lHaystack; active= 0; end = 0; /* Prepare new string */ newString = malloc(sizeof(char) * lNew + 1); newString[sizeof(char) * lNew] = 0; /* Build new string */ for (i = 0; i < lHaystack; i++) { if ( (!active) && (haystack[i] == needle[0])) { /* Start of needle found */ active = 1; start = i; end = i; } else if ( (active) && (i-start == lNeedle) ) { /* End of needle - apply replacement */ active = 0; for (k = 0; k < lReplace; k++) { newString[j] = replace[k]; j++; } newString[j] = haystack[i]; j++; } else if ( (active) && (i-start < lNeedle) && (haystack[i] == needle[i-start])) { /* Next part of needle found */ end++; } else if (active) { /* Didn't match the entire needle, so apply skipped chars */ active = 0; for (k = start; k < end+2; k++) { newString[j] = haystack[k]; j++; } } else if (!active) { /* No needle matched */ newString[j] = haystack[i]; j++; } } /* If still matching a needle... */ if ( active && (i-start == lNeedle)) { /* If full needle */ for (k = 0; k < lReplace; k++) { newString[j] = replace[k]; j++; } newString[j] = haystack[i]; j++; } else if (active) { for (k = start; k < end+2; k++) { newString[j] = haystack[k]; j++; } } return newString; } int main(void) { char *s = "Have a nice day!"; printf("Original: %s\n", s); printf("Replaced: %s\n", ReplaceString("nice", "fantastic", s)); return 0; }
Stay Subscribed
RSS feed or get updates by e-mail.
, subscribe to theYou can also contact me directly - I make an effort to reply to every e-mail.