c语言使用指定字符串替换特定的子串
生活随笔
收集整理的這篇文章主要介紹了
c语言使用指定字符串替换特定的子串
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言
當前程序是在linux環境下執行的
代碼
#include<stdio.h>
#include<stdlib.h>
#include<string.h>#define MAX_UTF8_RES_LEN 1024int 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
總結
以上是生活随笔為你收集整理的c语言使用指定字符串替换特定的子串的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python内置库之学习ctypes库(
- 下一篇: python内置库之学习ctypes库(