C语言字符串替换操作在C中的实现

发布时间:2024-08-30 12:09:44 作者:小樊
来源:亿速云 阅读:81

在C语言中,字符串替换操作可以通过自定义函数来实现

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

char *str_replace(const char *str, const char *old, const char *new) {
    char *result;
    int i, count = 0;
    int newlen = strlen(new);
    int oldlen = strlen(old);

    for (i = 0; str[i] != '\0'; i++) {
        if (strncmp(&str[i], old, oldlen) == 0) {
            count++;
            i += oldlen - 1;
        }
    }

    result = (char *)malloc(i + count * (newlen - oldlen) + 1);
    if (result == NULL) {
        printf("Memory allocation failed.\n");
        exit(1);
    }

    i = 0;
    while (*str) {
        if (strncmp(str, old, oldlen) == 0) {
            strcpy(&result[i], new);
            i += newlen;
            str += oldlen;
        } else {
            result[i++] = *str++;
        }
    }

    result[i] = '\0';
    return result;
}

int main() {
    const char *str = "Hello, world!";
    const char *old = "world";
    const char *new = "C Language";

    char *replaced = str_replace(str, old, new);
    printf("Original string: %s\n", str);
    printf("Replaced string: %s\n", replaced);

    free(replaced);
    return 0;
}

这个程序首先定义了一个名为str_replace的函数,该函数接受三个参数:原始字符串str、需要被替换的子字符串old和用于替换的新子字符串new。函数首先计算替换后的字符串长度,然后为结果字符串分配内存。接下来,函数遍历原始字符串,将不需要替换的部分复制到结果字符串中,并在遇到需要替换的子字符串时进行替换。最后,函数返回结果字符串。

main函数中,我们使用str_replace函数替换字符串中的"world"为"C Language",并输出原始字符串和替换后的字符串。注意,我们需要在程序结束时释放由str_replace函数分配的内存。

推荐阅读:
  1. c语言原码、反码、补码与位运算的概念是什么
  2. c语言中的0x是什么意思

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c语言

上一篇:如何反转C语言字符串内容

下一篇:C语言字符串分割技巧在C语言中的应用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》