编写一个字符替换函数rep(char *s,char*s1,char *s2),实现将已知的字符串所有属于字符串s1的字符全部用S2中的对应字符代替.
e.g:字符串s,s1,s2分别如下:
char s[]=''ABCABC'',s1[]='AC',s2[]=''xy''调用函数后 s的内容变成xByxBy 大家帮帮我啊
C语言字符替换
答案:3 悬赏:0
解决时间 2021-12-21 20:41
- 提问者网友:冥界祭月
- 2021-12-21 12:17
最佳答案
- 二级知识专家网友:风格单纯
- 2021-12-21 13:41
char *replace(char *source, char *sub, char *rep)
{
char *result;
char *pc1, *pc2, *pc3;
int isource, isub, irep;
isub = strlen(sub);
irep = strlen(rep);
isource= strlen(source);
if(NULL==*sub)
return strdup(source);
result = (char *)malloc(((irep>isub)?(float)strlen(source)/isub*irep+1:isource)*sizeof(char));
pc1 = result;
while(*source != NULL)
{
pc2 = source;
pc3 = sub;
while(*pc2==*pc3 && *pc3 != NULL && *pc2 != NULL)
pc2++, pc3;
if(NULL==*pc3)
{
pc3 = rep;
while(*pc3 != NULL)
*pc1 = *pc3;
pc2--;
source = pc2;
}
*pc1 = *source;
source;
}
*pc1 = NULL;
result;
}
{
char *result;
char *pc1, *pc2, *pc3;
int isource, isub, irep;
isub = strlen(sub);
irep = strlen(rep);
isource= strlen(source);
if(NULL==*sub)
return strdup(source);
result = (char *)malloc(((irep>isub)?(float)strlen(source)/isub*irep+1:isource)*sizeof(char));
pc1 = result;
while(*source != NULL)
{
pc2 = source;
pc3 = sub;
while(*pc2==*pc3 && *pc3 != NULL && *pc2 != NULL)
pc2++, pc3;
if(NULL==*pc3)
{
pc3 = rep;
while(*pc3 != NULL)
*pc1 = *pc3;
pc2--;
source = pc2;
}
*pc1 = *source;
source;
}
*pc1 = NULL;
result;
}
全部回答
- 1楼网友:随心随缘不随便
- 2021-12-21 15:36
用两个for循环,
对s中中每一个字符,与s1中的所有字符比较,然后作一个if判断,如果存在相等情况,就替换就行啦
- 2楼网友:一只傻青衣
- 2021-12-21 14:58
#include <stdio.h>
void match(char s[ ],char c1, char c2);
int main()
{
char s[]="hello world";
char c1,c2;
printf("请输入要被替换的字母:");
scanf("%c",&c1);
getchar();
printf("请输入替换的字母:");
scanf("%c",&c2);
match(s,c1,c2);
puts(s);
}
void match (char s[ ],char c1, char c2)
{
int i=0;
while(s[i]!='\0')
{
if(s[i]==c1)
s[i]=c2;
i++;
}
}
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯