how to replace substring in c?

前端 未结 4 1691
[愿得一人]
[愿得一人] 2020-12-06 21:20

This example works but I think that the memory leaks. Function used in the simple web server module and thus shared memory grows if you use this function.

          


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-06 21:46

    One problem I can see is that if the replacement string contains the search string, you'll loop forever (until you run out of memory).

    For example:

    char *result = str_replace("abc", "a", "aa");
    

    Also, doing another malloc/free every time you replace one instance is pretty expensive.

    A better approach would be to do exactly 2 passes over the input string:

    • the first pass, count how many instances of the search string are present

    • now that you know how many matches, compute the length of your result & malloc once:

      strlen(string) + matches*(strlen(replacement)-strlen(substr)) + 1

    • make a second pass through the source string, copying/replacing

提交回复
热议问题