C 替换字符方法--1
#include "stdafx.h" //linux 底下要去掉这一行
#include <stdio.h>
#include<stdlib.h>
#include <string.h>
#include <malloc.h>
char matchStr1[]="111,aaa,ddd";
static char *strcpyNew(char *strDes, char *strSrc)
{
if(NULL==strSrc) return strDes;
strDes=(char *)malloc(strlen(strSrc)+1); //assign more 1 space to save'\0'
char *p=strDes;
while(*strSrc!='\0')
{
*p++=*strSrc++;
}
*p='\0';
return strDes;
}
static char * DelStr(char *sSrc, char *sMatchStr)
{
if(strcmp(sMatchStr,"")==0||(NULL==sSrc)||(sSrc==""))return sSrc;
char *seps =",";
char *token = strtok(sMatchStr, seps);
while(token)
{
char *FindPos = strstr(sSrc, token);
if(FindPos)
while(FindPos)
{
int i;
int newLen=strlen(sSrc);
int leftLen=FindPos - sSrc;
char *p=(char *)malloc(newLen);
for(i=0;i<leftLen;i++)
{
p[i]=sSrc[i];
}
for(i=leftLen;i<newLen;i++)
{
p[i]=sSrc[i+strlen(token)];
}
sSrc= strcpyNew(sSrc, p);
free(p);
FindPos = strstr(sSrc, token);
}
token = strtok(NULL, seps);
}
return sSrc;
}
int main(int argc, char* argv[])
{
char * abc="333 333 aaa aaa ddd 444 aaa 666";
printf("--原先--\n%s,size=%d\n",abc,strlen(abc));
abc=DelStr(abc,matchStr1);
printf("--现在--\n%s,size=%d\n",abc,strlen(abc));
return 0;
}
本文来自博客园,作者:aspirant,转载请注明原文链接:https://www.cnblogs.com/aspirant/p/3576306.html