For string, find and replace

前端 未结 6 949
盖世英雄少女心
盖世英雄少女心 2020-12-16 08:03

Finding some text and replacing it with new text within a C string can be a little trickier than expected. I am searching for an algorithm which is fast, and that has a smal

6条回答
  •  别那么骄傲
    2020-12-16 08:21

    My solution, based on the others, but a bit safer I believe:

    #include 
    #include 
    #include 
    #define MAX_SOURCE_SIZE (0x100000)
    
    char * searchReplace(char * string, char *toReplace[], char *replacements[], int numReplacements){
        int i = 0;
        char *locOfToRep;
        char *toRep;
        char *rep;
        int lenToRep,lenStr,lenAfterLocRep;
        static char buffer[MAX_SOURCE_SIZE];
        for(i = 0; i < numReplacements; ++i){
            toRep = toReplace[i];
            rep = replacements[i];
            //if str not in the string, exit.
            if (!(locOfToRep = strstr(string,toRep))){
               exit(EXIT_FAILURE);
            }
            lenToRep = strlen(toRep); 
            lenStr = strlen(string); 
            lenAfterLocRep = strlen(locOfToRep); 
    
            //Print the string upto the pointer, then the val, and then the rest of the string.
            sprintf(buffer, "%.*s%s%s", lenStr-lenAfterLocRep, string,rep,locOfToRep+lenToRep);
    
            string = buffer;
        }
        return buffer;
    }
    
    int main(){
        char * string = "Hello, world!";
        int numVals;
        char *names[2] = {"Hello", "world"};
        char *vals[2] = {"Goodbye", "you"};
        numVals = 2;
        string = searchReplace(string, names, vals, numVals);
        printf("%s\n",string);
    }
    

提交回复
热议问题