c语言使用指定字符串替换特定的子串

前言

当前程序是在linux环境下执行的

代码

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

#define MAX_UTF8_RES_LEN 1024

int replace_all(char* str, size_t strLen, const char* d, const char* s)
{
    char* pos = 0;
    char* prv = 0;
    char temp[MAX_UTF8_RES_LEN];
    memset(temp, 0, MAX_UTF8_RES_LEN);
    if(str == NULL || d == NULL || s == NULL)
    {
        printf("Init error\n");
    }
    *temp = 0;
    prv = str;
    pos = strstr(str, d);
    while (pos) {
        strncat(temp, prv, pos - prv);
        pos += strlen(d);
        prv = pos;
        pos = strstr(prv, d);
        strncat(temp, s, MAX_UTF8_RES_LEN - 1 - strlen(temp));
    }
    if (prv != str + strlen(str)) {
        strncat(temp, prv, MAX_UTF8_RES_LEN - 1 - strlen(temp));
    }
    if (strlen(temp) > strLen) {
        printf("Overflow!\n");
        return -1;
    }
    strncpy(str, temp, MAX_UTF8_RES_LEN - 1);
    str[MAX_UTF8_RES_LEN - 1] = '\0';
    return 0;
}

int
main(int argc, char* argv[])
{
    char * line = NULL;
    size_t len = 0;
    ssize_t read_len;
    while ((read_len=getline(&line, &len, stdin)) != -1) 
    {
        if (read_len > 0 && line[read_len-1] == '\n')
        { 
            line[read_len-1] = '\0';
            read_len -= 1;  
        }
        int b = replace_all(line, MAX_UTF8_RES_LEN, "888", "999");
        printf("b is %d\n", b);
        printf("new is %s\n", line);
    }
    return 0;
}

编译

gcc demo.cc -g -o demo

运行

echo "hello 888 asdfa 888888fa889sdfa" | ./demo 

结果

b is 0
new is hello 999 asdfa 999999fa889sdfa
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 代码科技 设计师:Amelia_0503 返回首页