问题描述
- csdn上别人提的问题,大神,能帮我改改吗?
-
#include<stdio.h> #include<stdlib.h> int main() { char s[]="I have an apple.Do you like apple?"; char s1[]="apple"; char s2[]="orange"; int i,j,k,h,p,c; for(p=0;s[p]!='';) p++; for(i=0;s[i]!='';i++) for(j=i,k=0;s1[k]==s[j];k++,j++) if(s1[k+1]=='') { for(i=j-k,h=0;s[i]!=''&&s2[h]!='';) { if(h>k) { for(c=p-1;c>=i;c--) s[c+1]=s[c]; } s[i++]=s2[h++]; } break; } printf("%sn",s); system("pause"); return 0; }
解决方案
/*#include
#include
char s1[50];
char s2[]={'a','p','p','l','e'};
char s3[]={'o','r','a','n','g','e'};
char target [100];
int i=0,j,count=0;
int main()
{
gets(s1);
while(s1[i]!='')
{
if((s1[i]==s2[0])&&(s1[i+1]==s2[1])&&(s1[i+2]==s2[2])&&(s1[i+3]==s2[3])&&(s1[i+4]==s2[4]))
{
for(j=0;j<strlen(s3);j++)
{
target[count]=s3[j];
count++;
}
i=i+5;
}
else
{
target[count]=s1[i];
count++;
i++;
}
}
puts(target);
return 0;
}
解决方案二:
在字符串结尾加上一个''
解决方案三:
晕,看了下,算法都有问题
解决方案四:
http://codepad.org/WwJCWbQU
#include
#include
#include
#define MAX_MSG_LENGTH 1000
int main()
{
char sSrc[1000]="I have an apple.Do you like apple?";
char sMatchStr[]="apple";
char sReplaceStr[]="orange";
int StringLen;
char caNewString[MAX_MSG_LENGTH];
char *FindPos = strstr(sSrc, sMatchStr);
while (FindPos)
{
memset(caNewString, 0, sizeof(caNewString));
StringLen = FindPos - sSrc;
strncpy(caNewString, sSrc, StringLen);
char * sReplaceStr1 = (char *)malloc(sizeof(char) * (strlen(sReplaceStr) + 1));
strncpy(sReplaceStr1, sReplaceStr, (strlen(sReplaceStr) + 1));
strcat(caNewString, sReplaceStr1);
strcat(caNewString, FindPos + strlen(sMatchStr));
strcpy(sSrc, caNewString);
FindPos += strlen(sMatchStr);
FindPos = strstr(FindPos, sMatchStr);
}
printf("%sn",sSrc);
}
写了一个给你
解决方案五:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_MSG_LENGTH 1000
int main()
{
char sSrc[1000]="I have an apple.Do you like apple?";
char sMatchStr[]="apple";
char sReplaceStr[]="orange";
int StringLen;
char caNewString[MAX_MSG_LENGTH];
char *FindPos = strstr(sSrc, sMatchStr);
while (FindPos)
{
memset(caNewString, 0, sizeof(caNewString));
StringLen = FindPos - sSrc;
strncpy(caNewString, sSrc, StringLen);
char * sReplaceStr1 = (char *)malloc(sizeof(char) * (strlen(sReplaceStr) + 1));
strncpy(sReplaceStr1, sReplaceStr, (strlen(sReplaceStr) + 1));
strcat(caNewString, sReplaceStr1);
strcat(caNewString, FindPos + strlen(sMatchStr));
strcpy(sSrc, caNewString);
FindPos += strlen(sMatchStr);
FindPos = strstr(FindPos, sMatchStr);
}
printf("%sn",sSrc);
}
解决方案六:
我按照我自己的改好了,我还是喜欢自己的算法,谢谢大家热心的回答
#include<stdio.h>
#include<stdlib.h>
int main()
{
char s[100]="I have an apple.Do you like apple?";
char s1[]="apple";
char s2[]="orange";
int i,j,k,h,p,c;
for(p=0;s[p]!='';)
p++;
for(i=0;i<p;i++)
for(j=i,k=0;s1[k]==s[j];k++,j++)
if(s1[k+1]=='')
{
for(i=j-k,h=0;i<p&&s2[h]!='';)
{
if(h>k)
{
for(c=p-1;c>=i;c--)
s[c+1]=s[c];
p++;
}
s[i++]=s2[h++];
}
break;
}
for(i=0;i<p;i++)
printf("%c",s[i]);
printf("n");
system("pause");
return 0;
}