- #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.
复制代码 |
|