题目要求使用C语言编译程序。
#include
char* Replace(char* str,char* substr,char*newstr)
{
unsigned short strLen,substrLen,newstrLen;
strLen=strlen(str);
substrLen=strlen(substr);
newstrLen=strlen(newstr);
static char res[100];
memset(res,0,sizeof(res));
if(strLen>99)
return;
short count=strLen-substrLen+1;
for(int i=0;i<count;i++)
{
char chr[100];
memset(chr,0,sizeof(res));
strcpy_s(chr,substrLen,str+i);
if(0==strcmp(chr,substr)&&i+newstrLen<sizeof(res))
{
strcat(res,newstr);
i+=(substrLen-1);
}
else
{
res[strlen(res)]=chr[0];
}
}
}
之前重装系统,vs暂时用不了所以没自己运行一下试试,正在配置环境……
//./str_replace_all "(uid=%u/%u)" "%u" chantra
char *str_replace(const char *string, const char *substr, const char *replacement )
{
char *tok = NULL;
char *newstr = NULL;
char *oldstr = NULL;
/* if either substr or replacement is NULL, duplicate string a let caller handle it */
if ( substr == NULL || replacement == NULL )
return strdup (string);
newstr = strdup (string);
while ( (tok = strstr( newstr, substr)))
{
oldstr = newstr;
newstr = malloc (strlen ( oldstr ) - strlen ( substr ) + strlen ( replacement ) + 1 );
/*failed to alloc mem, free old string and return NULL */
if (newstr == NULL)
{
free (oldstr);
return NULL;
}
memcpy ( newstr, oldstr, tok - oldstr );
memcpy ( newstr + (tok - oldstr), replacement, strlen ( replacement ) );
memcpy ( newstr + (tok - oldstr) + strlen( replacement ), tok + strlen ( substr ), strlen ( oldstr ) - strlen ( substr ) - ( tok - oldstr ) );
memset ( newstr + strlen ( oldstr ) - strlen ( substr ) + strlen ( replacement ) , 0, 1 );
free(oldstr);
}
return newstr;
}