簡單實現ReplaceAll(轉)

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;  
}


/************************************************************************/
/* @param src  要替換的字符串   
/* @param des  替換後的字符串存放
/* @param find 所要替換的字符串
/* @param replaceWith 要替換的字符串
/************************************************************************/
char* ReplaceAll(char* src,char *des, 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 = des; 
//初始化新字符串內存  
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;  
}  spa

相關文章
相關標籤/搜索