有效地替换字符串中的子字符串

时间:2021-05-25 19:20:35

I have made 2 functions that find a substring index and substitute that substring in the string. I'm glad I jury rigged this at all given that similar questions previously asked were never answered/marked as closed without any help. But any suggestions on a cleaner method?

我已经创建了2个函数来查找子字符串索引并替换字符串中的子字符串。我很高兴我的陪审团操纵了这一点,因为之前提出的类似问题在没有任何帮助的情况下从未被回答/标记为关闭。但有关更清洁方法的任何建议?

void destroy_substr(int index, int len)
{
    int i;

    for (i = index; i < len; i++)
    {
        string[i] = '~'; 
    }
}


void find_substr_index(char* substr)
{
    int i;
    int j;
    int k;  
    int count;
    int len = strlen(substr);

    for (i = 0; i < strlen(string); i++)
    {
        if (string[i] == substr[0])
        {
            for(j = i, k = 0; k < len; j++, k++)
            {
                if (string[j] == substr[k])
                {   
                    count++;
                }
                if (count == len)
                    destroy_substr((j - len + 1), len);
            }
            j = 0; 
            k = 0;
            count = 0;
        }
    } 
}

3 个解决方案

#1


2  

Your code seem like you're trying to re-inventing your own wheel.

您的代码似乎正在尝试重新发明自己的*。

By using standard C functions, which is strstr() and memset(), you can achieve the same result as you expected.

通过使用标准C函数(strstr()和memset()),您可以获得与预期相同的结果。

#include <stdio.h>
#include <string.h>

char string[] = "foobar foobar foobar";
char substr[] = "foo";
char replace = '~';

int main() {

    int substr_size = strlen(substr);

    // make a copy to your `string` pointer
    // this is to ensure we can safely modify this pointer value, without 'touching' the original one
    char *ptr = string;

    // while true (infinite loop)
    while(1) {

        // find pointer to next substring
        ptr = strstr(ptr, substr);

        // if no substring found, then break from loop
        if(ptr == NULL) { break; }

        // if found, then replace it with your char
        memset(ptr, replace, substr_size);

        // increment our string pointer, pass replaced substring
        ptr += substr_size;
    }

    printf("%s\n", string);

    return 0;
}

#2


0  

How about this:

这个怎么样:

#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
{
    char string[] = "HELLO hello WORLD world HELLO hello ell";
    char substring[] = "ell";
    int stringLength = strlen(string);
    int substringLength = strlen(substring);

    printf("Before: %s\n", string);

    if(substringLength <= stringLength)
    {
        int i;
        int j;

        for(i = 0, j = stringLength - substringLength + 1; i < j; )
        {
            if(memcmp(&string[i], substring, substringLength) == 0)
            {
                memset(&string[i], '~', substringLength);
                i += substringLength;
            }
            else
            {
                i++;
            }
        }
    }

    printf("After: %s\n", string);

    return 0;
}

Key ideas are:

主要想法是:

  1. You only need to scan the string (stringLength - substringLength) times
  2. 您只需要扫描字符串(stringLength - substringLength)次
  3. You can use functions from string.h to do the comparison and to replace the substring
  4. 您可以使用string.h中的函数进行比较并替换子字符串

#3


0  

You can copy the new string in place. If you want to support insertion of longer strings you will need to manage memory with malloc()/realloc(). If you want to support insertion of smaller strings you'll need to advance the pointer to the beginning by the length of the replacement string, copy the rest of the string to that new location, then zero the new end of the string.

您可以复制新字符串。如果要支持插入更长的字符串,则需要使用malloc()/ realloc()来管理内存。如果要支持插入较小的字符串,则需要将指针前移到替换字符串的长度,将字符串的其余部分复制到该新位置,然后将字符串的新结尾调零。

#include <stdio.h>
#include <string.h>
#include <err.h>

int main(int argc, char **argv)
{   
    char *str = strdup("The fox jumps the dog\n");
    char *search = "fox";
    char *replace = "cat";
    size_t replace_len = strlen(replace);
    char *begin = strstr(str, search);

    if (begin == NULL)  
        errx(1, "substring not found");

    if (strlen(begin) < replace_len)
        errx(1, "replacement too long");

    printf("%s", str);
    memcpy(begin, replace, replace_len);
    printf("%s", str);

    return 0;
}

#1


2  

Your code seem like you're trying to re-inventing your own wheel.

您的代码似乎正在尝试重新发明自己的*。

By using standard C functions, which is strstr() and memset(), you can achieve the same result as you expected.

通过使用标准C函数(strstr()和memset()),您可以获得与预期相同的结果。

#include <stdio.h>
#include <string.h>

char string[] = "foobar foobar foobar";
char substr[] = "foo";
char replace = '~';

int main() {

    int substr_size = strlen(substr);

    // make a copy to your `string` pointer
    // this is to ensure we can safely modify this pointer value, without 'touching' the original one
    char *ptr = string;

    // while true (infinite loop)
    while(1) {

        // find pointer to next substring
        ptr = strstr(ptr, substr);

        // if no substring found, then break from loop
        if(ptr == NULL) { break; }

        // if found, then replace it with your char
        memset(ptr, replace, substr_size);

        // increment our string pointer, pass replaced substring
        ptr += substr_size;
    }

    printf("%s\n", string);

    return 0;
}

#2


0  

How about this:

这个怎么样:

#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
{
    char string[] = "HELLO hello WORLD world HELLO hello ell";
    char substring[] = "ell";
    int stringLength = strlen(string);
    int substringLength = strlen(substring);

    printf("Before: %s\n", string);

    if(substringLength <= stringLength)
    {
        int i;
        int j;

        for(i = 0, j = stringLength - substringLength + 1; i < j; )
        {
            if(memcmp(&string[i], substring, substringLength) == 0)
            {
                memset(&string[i], '~', substringLength);
                i += substringLength;
            }
            else
            {
                i++;
            }
        }
    }

    printf("After: %s\n", string);

    return 0;
}

Key ideas are:

主要想法是:

  1. You only need to scan the string (stringLength - substringLength) times
  2. 您只需要扫描字符串(stringLength - substringLength)次
  3. You can use functions from string.h to do the comparison and to replace the substring
  4. 您可以使用string.h中的函数进行比较并替换子字符串

#3


0  

You can copy the new string in place. If you want to support insertion of longer strings you will need to manage memory with malloc()/realloc(). If you want to support insertion of smaller strings you'll need to advance the pointer to the beginning by the length of the replacement string, copy the rest of the string to that new location, then zero the new end of the string.

您可以复制新字符串。如果要支持插入更长的字符串,则需要使用malloc()/ realloc()来管理内存。如果要支持插入较小的字符串,则需要将指针前移到替换字符串的长度,将字符串的其余部分复制到该新位置,然后将字符串的新结尾调零。

#include <stdio.h>
#include <string.h>
#include <err.h>

int main(int argc, char **argv)
{   
    char *str = strdup("The fox jumps the dog\n");
    char *search = "fox";
    char *replace = "cat";
    size_t replace_len = strlen(replace);
    char *begin = strstr(str, search);

    if (begin == NULL)  
        errx(1, "substring not found");

    if (strlen(begin) < replace_len)
        errx(1, "replacement too long");

    printf("%s", str);
    memcpy(begin, replace, replace_len);
    printf("%s", str);

    return 0;
}