【前言】
下面两种算法结果测试都是对的,测试的句子中英语语法(捂脸)不对,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;
}
【测试结果】