1. 程式人生 > >c語言使用指定字串替換特定的子串

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