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

标签 c

我创建了两个函数,用于查找子字符串索引并替换字符串中的子字符串。我很高兴陪审团完全操纵了这个,因为之前提出的类似问题从未在没有任何帮助的情况下得到回答/标记为关闭。有更清洁的方法吗?

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;
        }
    }
}

最佳答案

您的代码看起来像是在尝试重新发明自己的轮子。

通过使用标准 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 of 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 the loop
        if(ptr == NULL) { break; }

        // If found, then replace it with your character
        memset(ptr, replace, substr_size);

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

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

    return 0;
}

关于c - 有效地替换字符串中的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35595389/

相关文章:

c - 读取BMP文件并旋转

c++ - 什么是 uint_fast32_t,为什么要使用它来代替常规的 int 和 uint32_t?

c - 修改我也有一个 const 指针指向的值是否是未定义的行为

c - 指针数组中的未初始化或 NULL 指针

c - bss 和数据的最大大小

c - 斯坦福 GraphBase .gb 格式

c - 以最优方法在链表中找到最小值

c - 为什么我的 shell 程序不打开它在函数 "cat"中作为参数接收的文件

c - 为什么挂载结构有两个挂载点字段?

c - 如何在 C 中使用 rand() 函数和范围