7.10写一个函数,输入一行字符,将此字符串中最长的单词输出。

//C程序设计第四版(谭浩强)
//章节:第七章 用函数实现模块化程序设计
//题号:7.10
//题目:写一个函数,输入一行字符,将此字符串中最长的单词输出。
#include <stdio.h>
#include <string.h>
void longestword(char s[])
{
	char t[30],temp[30];
	t[0]='\0';
	int len=strlen(s),i,j=0;
	for(i=0;i<len;i++)
	{
		j=0;
		while(s[i]>='a'&&s[i]<='z'||s[i]>='A'&&s[i]<='Z')
			temp[j++]=s[i++];	//将由非字母字符分割成的每个单词临时储存在temp[]中 
		temp[j]='\0';
		if(strlen(t)<strlen(temp))	//t[]为储存最长单词的字符数组 
			strcpy(t,temp);	//通过比较t、temp字符数组的长度,判断当前最长单词并将其储存在t中 
		}
	}
	printf("the longest word:\n");
	puts(t);
}
int main()
{
	char s[81];	//一行字符最多有81个字符 
	printf("input string:\n");
	gets(s);
	longestword(s);
	return 0;
 } 

猜你喜欢

转载自blog.csdn.net/weixin_44589540/article/details/86622570