日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

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

發布時間:2023/11/28 生活经验 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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语言使用指定字符串替换特定的子串的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。