[不是问题]找到句子中最长的单词。如果句子有多个相同长度的单词,你应该选择第一个单词。 [英] [Not a question] find the longest word in a sentence. If the sentence has more than one word of the same length you should pick the first one.

查看:86
本文介绍了[不是问题]找到句子中最长的单词。如果句子有多个相同长度的单词,你应该选择第一个单词。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>

int main()
{
	char str[100],sav[100],tmp[100];
	int i,count=0,k=0,len,flag,a[10];

	printf("Enter string:");
	gets(str);

	printf("\nYou entered:");
	puts(str);
	printf("\n");
	len=strlen(str);


	while(1)
	{
		for(i=0;str[i]!='\0';i++)
		{
			count++;
			sav[i]=str[i];

			if(str[i] == ' ' || str[i] !='\0')
			{
				if(k<count)>
				{
					printf("No. of words is:%d\n",count);
					k=count;
					printf("Words separated by spaces:");
					puts(sav);
					printf("\n");
				}
				count = 0;
			}
		}
	}

	return 0;

}

推荐答案

这是作业,我们不做作业! :笑:



但你的代码不起作用,因为你没有告诉它做你想做的事 - 它不看字符串并计算出任何单词长度,你必须先弄清楚哪个单词最长。



最简单的方法是创建三个函数

1)获取用户字符串。

2)找到每个单词。

3)找到最长的单词。



这样,你的代码变得更简单,读取和写入都更加明显。



我不确定建议你这样做的方法,但是......你知道如何设置数组吗?什么指针是什么?
This is homework, and we don't do homework! :laugh:

But your code doesn't work, because you haven't told it to do what you want it to - it doesn't look at the string and work out any word lengths, which you have to do before you can work out which word is longest.

The easiest way to do this is to create three functions
1) get the user string.
2) find each word.
3) find the longest word.

That way, you code becomes a long simpler, and more obvious to both read, and write.

I'm not sure which way to suggest you do this, but... Do you know how to set up arrays? And what pointers are?


这篇关于[不是问题]找到句子中最长的单词。如果句子有多个相同长度的单词,你应该选择第一个单词。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆