> 其他 >
C程序有道题解析看不懂
编写一个程序求出两个字符串:
s[]=”Thisis C programming text”
t[]=”Thisis a text for C programming”
包含最长的相同单词(同一字母的大小写视为不同的字符).
程序:
#include
#include
void maxword(char *s,char *t)
{
char*res,*temp,chs,cht;
inti,j,found,maxlen=0;
while(*s!='\0')
{
while(*s==' ') s++;
for(i=0;s[i]!=' ' && s[i]!='\0';i++);
if(i>maxlen)
{
chs=s[i];
s[i]='\0';
temp=t;
found=0;
while (*temp!='\0' && found)
{
while (*temp==' ') temp++;
for (j=0;temp[j]!=' ' && temp[j]!='\0';j++);
if (j==i)
{
cht=temp[j];
temp[j]='\0';
if (strcmp(s,temp)==0)
{
maxlen=i;
res=s;
found=1;
}
temp[j]=cht;
}
temp=&temp[j];
}
s[i]=chs;
}
s=&s[i];
}
if(maxlen==0)
printf("没有相同的单词.\n");
else
{
chs=res[maxlen];
res[maxlen]='\0';
printf("%s\n",res);
res[maxlen]=chs;
}
}
main()
{
staticchar s[]="This is C programming text";
staticchar t[]="This is a text for C programming";
maxword(s,t);
}
看不懂,关键步骤的每一步是干什么用的,设置的每个变量分别起什么作用.
人气:124 ℃ 时间:2020-05-19 00:33:19
解答
/*将字符串s中的第一个单词,与字符串t中的所有单词比较,看单词是否相等.然后s中的第二个单词比较,这样依次循环*/#include #include void maxword(char *s,char *t){char *res,*temp,chs,cht;int i,j,found,maxlen=0;...*res,*temp,chs,cht; ���ĸ������ֱ��Ǹ����õ�for (j=0;temp[j]!=' ' && temp[j]!='\0';j++); ���ִ�к��jΪ������ʵĺ�һ��λ�ã�Ҳ���ǵ���λ��ֻ��j-1,������chs=temp[j]�� ���Ƿ���jλ����ݵı�����ͬ��chtҲ�ǡ�*res���Ǵ���ҵ��ĵ��ʡ�temp=t������temp��t�ַ���в���������for (j=0;temp[j]!=' ' && temp[j]!='\0';j++);ִ�����temp[0]��temp[j-1]Ϊ���ʣ���temp[j]='\0',��ʱtemp�ַ�����������ҵ��ĵ��ʡ�
推荐
猜你喜欢
© 2024 79432.Com All Rights Reserved.
电脑版|手机版