Created
April 23, 2021 14:24
-
-
Save zer0cat/c63a3346453eef033b2a267e6e48af23 to your computer and use it in GitHub Desktop.
String replace in pure C
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
| /* | |
| * @brief | |
| * PHP's str_replace ported to C | |
| * @author Silver Moon (m00n.silv3r@gmail.com) | |
| * */ | |
| #include<stdio.h> | |
| #include<string.h> | |
| #include<stdlib.h> | |
| char *str_replace(char *search , char *replace , char *subject); | |
| int main() | |
| { | |
| char *a = "allblldddlll"; | |
| char *c = str_replace("ll" , "xll" , a); | |
| puts(c); | |
| return 0; | |
| } | |
| /* | |
| * Search and replace a string with another string , in a string | |
| * */ | |
| char *str_replace(char *search , char *replace , char *subject) | |
| { | |
| char *p = NULL , *old = NULL , *new_subject = NULL ; | |
| int c = 0 , search_size; | |
| search_size = strlen(search); | |
| //Count how many occurences | |
| for(p = strstr(subject , search) ; p != NULL ; p = strstr(p + search_size , search)) | |
| { | |
| c++; | |
| } | |
| //Final size | |
| c = ( strlen(replace) - search_size )*c + strlen(subject); | |
| //New subject with new size | |
| new_subject = malloc( c ); | |
| //Set it to blank | |
| strcpy(new_subject , ""); | |
| //The start position | |
| old = subject; | |
| for(p = strstr(subject , search) ; p != NULL ; p = strstr(p + search_size , search)) | |
| { | |
| //move ahead and copy some text from original subject , from a certain position | |
| strncpy(new_subject + strlen(new_subject) , old , p - old); | |
| //move ahead and copy the replacement text | |
| strcpy(new_subject + strlen(new_subject) , replace); | |
| //The new start position after this search match | |
| old = p + search_size; | |
| } | |
| //Copy the part after the last search match | |
| strcpy(new_subject + strlen(new_subject) , old); | |
| return new_subject; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment