黑马程序员技术交流社区
标题:
基测--字符串查找最长单词
[打印本页]
作者:
wanderingman
时间:
2015-2-3 22:23
标题:
基测--字符串查找最长单词
#include<stdio.h>
#include <stdlib.h>
#define N 1000
longest_char(int max_len,char *a);
int b,s,n ; //定义最长单词开始位置为b,结束位置为s.
main()
{
char a[N];
int max_len = 0; //max_len 存放最长单词长度
printf("Please enter a string,separated by space:\n");
fgets(a,N,stdin);
longest_char(max_len,a);
max_len = longest_char(max_len,a);
printf("The longest word is :\n ");
for(;b<s;b++)
printf("%c",a[b]);
printf("\nThe longest word has %d chars.\n",max_len);
}
longest_char(int max_len, char *a)
{
int i=0 ;
while(a[i]!='\0')
{
n=0;
while(a[i]!=' ')
{
if (a[i]=='\0')
{
break;
}
n++;
i++;
}
if(n>max_len){max_len=n;s=i;b=s-max_len;}
i++;
}
return max_len ; //返回最长单词长度 。
}
输出结果:
Please enter a string,separated by space:
hello world thanksfor your great support
The longest word is :
thanksfor
The longest word has 9 chars.
Process returned 31 (0x1F) execution time : 13.830 s
Press any key to continue.
复制代码
作者:
wanderingman
时间:
2015-2-3 22:24
欢迎拍砖......
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2