C語言編寫的ReplaceAll函數
#include <stdio.h>include <malloc.h>
include <string.h>
char replaceAll(char src, char find, char replaceWith){ //如果find或者replace為null,則返回和src一樣的字符串。 if(find == NULL || replaceWith == NULL){ return strdup(src); } //指向替換后的字符串的head。 char afterReplaceHead = NULL; //總是指向新字符串的結尾位置。 char afterReplaceIndex = NULL; //find字符串在src字符串中出現的次數 int count = 0; int i,j,k;
int srcLen = strlen(src); int findLen = strlen(find); int replaceWithLen = strlen(replaceWith); //指向src字符串的某個位置,從該位置開始復制子字符串到afterReplaceIndex,初始從src的head開始復制。 char* srcIndex = src; //src字符串的某個下標,從該下標開始復制字符串到afterReplaceIndex,初始為src的第一個字符。 int cpStrStart = 0; //獲取find字符串在src字符串中出現的次數 count = getFindStrCount(src, find); //如果沒有出現,則返回和src一樣的字符串。 if(count == 0){ return strdup(src); } //為新字符串申請內存 afterReplaceHead = afterReplaceIndex = (char*)malloc(srcLen + 1 + (replaceWithLen - findLen) * count); //初始化新字符串內存 memset(afterReplaceHead, '\0',sizeof(afterReplaceHead)); for(i = 0,j = 0,k = 0;i!=srcLen;i++){ //如果find字符串的字符和src中字符串的字符是否相同。 if(src[i] == find[j]){ //如果剛開始比較,則將i的值先賦給k保存。 if(j == 0){ k = i; } //如果find字符串包含在src字符串中 if(j == (findLen-1)){ j = 0; //拷貝src中find字符串之前的字符串到新字符串中 strncpy(afterReplaceIndex, srcIndex, i - findLen - cpStrStart + 1); //修改afterReplaceIndex afterReplaceIndex = afterReplaceIndex + i - findLen - cpStrStart + 1; //修改srcIndex srcIndex = srcIndex + i - findLen - cpStrStart + 1; //cpStrStart cpStrStart = i + 1; //拷貝replaceWith字符串到新字符串中 strncpy(afterReplaceIndex, replaceWith, replaceWithLen); //修改afterReplaceIndex afterReplaceIndex = afterReplaceIndex + replaceWithLen; //修改srcIndex srcIndex = srcIndex + findLen; }else{ j++; } }else{ //如果find和src比較過程中出現不相等的情況,則將保存的k值還給i if(j != 0){ i = k; } j = 0; } } //最后將src中最后一個與find匹配的字符串后面的字符串復制到新字符串中。 strncpy(afterReplaceIndex, srcIndex, i - cpStrStart); return afterReplaceHead;
}
int getFindStrCount(char src, char find){ int count = 0; char* position =src; int findLen = strlen(find); while((position = strstr(position, find)) != NULL){ count++; position = position + findLen; } return count; }
int main(void){ char s = "12345345443344341334542345"; //調用函數replaceAll,s為源字符串,"345"為需要替換的字符串,”7890“為替換目的字符串。 char r = replaceAll(s, "345", "7890"); printf("%s\n",r); //使用replaceAll函數后一定要free掉,因為replace內部會malloc結果字符串的內存。 free(r); return 0; }</pre>