输入一行字符,输出最长的单词

来源:互联网 发布:linux批量解压缩zip 编辑:程序博客网 时间:2024/06/08 06:01
1、确定单词分隔符,一般情况为空格和标点符号,根据题目情况来确定标点符号是否算在单词中。 假定单词不包括标点符号,即全由字母组成
2、根据上面的特点,读取一个单词
3、计算单词长度
4、与当前最大单词长度max(初值为0)比较,如果大于max,则记录下当前单词,并将其长度赋值给max
5、重复2-4,直到读单词结束(到字符串尾)。

6、输出最长单词长度和单词。

#include<stdio.h>#include<string.h>#define M 1000        int main(){    int low;        // 单词的起始下标    int high;        // 单词的结束位置    int i;            // 循环变量     int count;        // 统计最长单词的长度    int temp;        // 中间变量     int low_temp;    int high_temp;    char p[M];        // 存储有多个单词的字符指针    gets(p);          //读入字符窜     count = 0;     low = 0;    high = 0;    for(i = 0; i < strlen(p); i++)    {        temp = 0;         low_temp = i;        while(p[i] != ' ' && p[i] != '\0')    // p[i] != 空格         {             temp++;             i++;         }        high_temp = i-1;        if(temp > count)        {            count = temp;            low = low_temp;            high = high_temp;        }    }    for(i = low; i <= high; i++)    {        putchar(p[i]);    }    return 0;}


0 0
原创粉丝点击