统计最长单词长度,以及位置

【前言】

下面两种算法结果测试都是对的,测试的句子中英语语法(捂脸)不对,really应该写为real,若改回real这就不能体现出最长单词的长度了(强行解释)。。。

【参考答案后改进算法】

#include <stdio.h>
#include <math.h>
#define maxSize 100

void fun(char s[])
{
	int i;
	int len, pos;
	int max, maxpos;

	i = 0;
	len = 0;
	pos = -1;
	max = 0;

	while (s[i] != '\0')
	{
		while ((s[i] >= 'A'&&s[i] <= 'Z') || (s[i] >= 'a'&&s[i] <= 'z'))
		{
			pos = i;
			++len;
			++i;
		}
		if (len > max)
		{
			max = len;
			maxpos = pos - max + 1;//写成i-max也是ok的
		}

		len = 0;

		while (!((s[i] >= 'A'&&s[i] <= 'Z') || (s[i] >= 'a'&&s[i] <= 'z')))
		{
			if (s[i] == '\0')
			{
				break;
			}
			++i;

		}

	}

	printf("%d %d", max, maxpos);
}



int main()
{
	char s[maxSize] = "I love you. It is a really fact.";
	fun(s);

	return 0;
}

【原算法】

#include <stdio.h>
#include <math.h>
#define maxSize 100

void fun(char s[])
{
	int i;
	int len, pos;
	int max, maxpos;

	i = 0;
	len = 0;
	pos = -1;
	max = 0;
	maxpos = -1;

	while (s[i] != '\0')
	{
		if ((s[i] >= 'A'&&s[i] <= 'Z') || (s[i] >= 'a'&&s[i] <= 'z'))
		{
			len++;

			if (len == 1)
				pos = i;

			if (len > max)
			{
				max = len;
				maxpos = pos;
			}
		}
		else
		{
			len = 0;
			pos = -1;
		}
		++i;

	}

	printf("%d %d", max, maxpos);
}



int main()
{
	char s[maxSize] = "I love you. It is a really fact.";
	fun(s);

	return 0;
}

【测试结果】

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值