[C語言] 字串取代(str | string replace c
strlen,strcpy,strstr,strcat,malloc#include
/* str_replace [字串取代]* @param {char*} source 原始的文字* @param {char*} find 搜尋的文字 * @param {char*} rep 替換的文字* */char *str_replace (char *source, char *find, char *rep){// 搜尋文字的長度int find_L=strlen(find);// 替換文字的長度int rep_L=strlen(rep);// 結果文字的長度int length=strlen(source)+1;// 定位偏移量int gap=0;
// 建立結果文字,並複製文字char *result = (char*)malloc(sizeof(char) * length);strcpy(result, source);
// 尚未被取代的字串char *former=source;// 搜尋文字出現的起始位址指標char *location= strstr(former, find);
// 漸進搜尋欲替換的文字while(location!=NULL){// 增加定位偏移量gap+=(location - former);// 將結束符號定在搜尋到的位址上result[gap]=;
// 計算新的長度length+=(rep_L-find_L);// 變更記憶體空間result = (char*)realloc(result, length * sizeof(char));// 替換的文字串接在結果後面strcat(result, rep);// 更新定位偏移量gap+=rep_L;
// 更新尚未被取代的字串的位址former=location+find_L;// 將尚未被取代的文字串接在結果後面strcat(result, former);
// 搜尋文字出現的起始位址指標location= strstr...