#include <malloc.h>
#include <memory.h>
#include <string.h>
char *replace(char *str, const char *before, const char* after)
{
if (strcmp(before, after) == 0)
return str
char *ps = str
char* tmps
int fl
while (ps = strstr(ps, before))
{
tmps = (char*)malloc(ps - str + strlen(after) + 1)
memcpy(tmps, str, ps - str)
*(tmps + (ps - str)) = 0
strcat(tmps, after)
ps += strlen(before)
tmps=(char*)realloc(tmps, strlen(tmps) + strlen(ps) + 1)
fl = strlen(tmps)
strcat(tmps, ps)
strcpy(str, tmps)
ps = str + fl
free(tmps)
}
return str
}
int main()
{
char str[200] = "1223344222333444"
printf("%s\n", replace(str, "22", "ABC"))
return 0
}
#include<stdio.h>
#include <malloc.h>
#include <string.h>
char* fstr(char* str, const char* subs)
{
char* t = (char*)malloc(strlen(subs) + 1)
char* ps = str
int i
int slen = strlen(subs)
*(t + slen) = 0
while (strlen(ps) >= slen)
{
for (i = 0 i < slen ++i)
{
*(t + i) = *(ps + i)
}
if (strcmp(t, subs) == 0)
{
free(t)
return ps
}
++ps
}
free(t)
return NULL
}
char *replace(char *str, const char *before, const char* after)
{
if (strcmp(before, after) == 0)
return str
char *ps = str
char* tmps
int fl,i
while (ps = fstr(ps, before))
{
tmps = (char*)malloc(ps - str + strlen(after) + 1)
for (i = 0 i < ps - str ++i)
*(tmps + i) = *(str + i)
*(tmps + (ps - str)) = 0
strcat(tmps, after)
ps += strlen(before)
tmps = (char*)realloc(tmps, strlen(tmps) + strlen(ps) + 1)
fl = strlen(tmps)
strcat(tmps, ps)
strcpy(str, tmps)
ps = str + fl
free(tmps)
}
return str
}
int main()
{
char str[200] = "1223344222333444"
printf("%s\n", replace(str, "22", "ABC"))
return 0
}
运行结果:其中包含的函数有:
void
search(char
*str,char
*sub_str)
//查找字符串str中sub_str出现的位置和个数
char
*replace(char
*str,char
*sub_str,char
*new_str)//把字符串str中的sub_str替换成new_str,并返回替换后的字符串
int
length(char
*str)
//返回str的长度
void
copy(char
*str1,char
*str2)
//把字符串str2复制给str1
源代码见附件。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)