c语言库函数【string.h】之 strrep_(char *src, char* oldStr, char * newStr)
代码如下:
#include<assert.h>
#include<stdio.h>
char * strrep_(char *src, char* oldStr, char * newStr)
{
if(src == NULL || *src == '/0')
return (char *) NULL;
if(oldStr == NULL || *oldStr == '/0' || newStr == NULL || *newStr == '/0')
return src;
char * pOld=oldStr;//旧字符串指针
char * pNew=newStr;//新字符串指针
int sLen=strlen_(src);//源字符串长度,或者调用系统strlen函数,记得引入<string.h>文件
int oLen=strlen_(oldStr);//旧字符串长度
int nLen=strlen_(newStr);;//新字符串长度
//存储结果的字符串
char * result=(char *)malloc( (oLen < nLen ? (float) sLen/oLen*nLen :sLen) * sizeof(char) );//分配空间
char * pRes=result;//指向结果字符串首地址
while(*src)//遍历源字符串
{
pOld=oldStr;//指向旧字符串首字符
while(*pOld && *src && *pOld == *src)//在源字符串中匹配旧字符串
{
pOld++;
src++;
}
if('/0' == *pOld)//匹配成功
{
pNew=newStr;//指向新字符串首字符
while(*pNew)//将新字符串赋给result
*pRes++ = *pNew++;
}
else//匹配不成功
{
*pRes++ = *src++;//将源字符串的字符赋给result,并后移源字符串指针
}
}
*pRes='/0';//添加结束字符
return result;//返回结果字符首地址
}