问题描述:

I need to write my own implementation of a function which finds a string (word1) in another string (text) and replaces all instances of word1 in text with a third string (word2).

This is what I have thus far;

void findandreplace(char text[],const char word1[], const char word2[])

{

char *start;

char *end;

start=strstr(text,word1);

end=start;

if (strcmp(text,start))

{

end+=strlen(word2);

strcpy(&text[end-start+1],&text[(int)start]);

strcpy(text,word2);

findandreplace(end,word1,word2);

}

if (!strcmp(text,start))

{

end++;

findandreplace(end,word1,word2);

}

if (!text)

{

return;

}

}

I'm sure I have made plenty of mistakes in writing this, but please keep in mind I am essentially a complete noob. Any help pointing out mistakes and possible corrections would be greatly appreciated.

网友答案:

This code works properly. Note, that it assumes word1 and word2 to be of equal length, therefore it is merely an idea of how could it be done, not final solution.

void findandreplace(char text[], const char word1[], const char word2[])  
{
    if(strlen(word1) == strlen(word2) &&   
        strcmp(word1, word2)) // The same lengths and words aren't equal to each other.
    {
        char *start;
        // start=strstr(text, "good"); // We don't seek string "good",
        start = strstr(text, word1);  // but string word1[].
        while(start != NULL)
        {
            strncpy(start, word2, strlen(word2));
            start = strstr(text, word1);
        }
    }
}  

Referring to your code:

  • start points to substring "good" (if exists), but you want to search for word1[].
  • text[(int)start] - casting pointer to int makes no sense. If you want to obtain index in text[] to which start points, you need to use pointer arithmetic: text[start - text].
  • strcpy(text, word2) will make text[] an actual copy of word2 string, what you need is strncpy(..)
相关阅读:
Top