我是一名在校大学生,初次写博客,希望各位大佬不喜勿喷,这个小程序,仅供参考,希望对大家有所帮助。
首先,分析题意,我们需要将一句话里面的单词数量统计出来,才能比较哪个单词最长。
所以,我们遍历字符串数组,以空格为单词的结束符标识,定义三个参数,start(单词的开始下标位置),end(单词的结束下标位置),length(单词的长度)。
在for循环执行的时候,我们先对end进行赋值,然后llength=end-start,最后对start赋值。具体代码如下所示。
在这个程序中,我们最后并没有按照传统的方法,使用 spilt() 函数将字符串数组按照单词拆分插入到一个新的数组中,而是定义一个参数 j ,存储当前length最大的时候的start值,这样我们最后就可以将最长单词储存并输出出来。
1 #include <stdio.h> 2 //------------------------定义数组长度 3 #define N 20 4 //------------------------函数声明 5 void Entering(char *str,int n); 6 void Export(char str[],int n); 7 void LongestWord(char str1[],char *str2,int n,int *a); 8 int main(){ 9 int a=0; 10 char str1[N]; 11 char str2[N]; 12 Entering(str1,N); 13 LongestWord(str1,str2,N,&a); 14 Export(str2,a); 15 return 0; 16 } 17 //------------------------输入 18 void Entering(char *str,int n){ 19 int i; 20 printf("请输入str:"); 21 for(i=0;i<n;i++) 22 { 23 scanf("%c",&str[i]); 24 } 25 } 26 //------------------------输出 27 void Export(char str[],int n) 28 { 29 int i; 30 for(i=0;i<=n;i++) 31 { 32 printf("%c",str[i]); 33 } 34 printf("\n"); 35 } 36 //------------------------最长单词 37 void LongestWord(char str1[],char *str2,int n,int *a) 38 { 39 printf("---------最长单词---------\n"); 40 int i,j,length=0,start=0,end=0; 41 for(i=0,j=0;i<n;i++) 42 { 43 if(str1[i]==\' \') 44 { 45 end=i; 46 if(length<end-start) 47 { 48 j=start; 49 length=end-start; 50 } 51 start=i+1; 52 } 53 } 54 for(i=0,j;j<end;i++,j++) 55 { 56 str2[i]=str1[j]; 57 } 58 *a=length; 59 } 60 /* 61 (样例输入:) 62 请输入str:I wrote a function. It was my first function. 63 (样例输出:) 64 function 65 */