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

 

void findLongestWord(char str[])
{
    int max = 0, //最长单词的长度
        len = 0;//每个单词的长度
    int startingIndex = 0, endIndex = 0;
    int strIndex = 0;//数组下标(控制循环)

    while (str[strIndex] != '\0')
    {
        if (str[strIndex] != ' ')
        {
            len++;
        }
        else
        {
            if (max < len)
            {
                max = len;
                startingIndex = strIndex - max; //最长的单词的开始的下标等于数组元素为空格的下标减去单词长度
                endIndex = strIndex;
            }
            len = 0;
        }
        strIndex++;
    }

    if (max < len)    //判断最后一个单词是否比最长的单词长
    {
        max = len;
        startingIndex = strIndex - max;
        endIndex = strIndex;
    }

    printf("The longest word is: ");
    for (int k = startingIndex; k < endIndex; k++)
        printf("%c", str[k]);
    printf("\n");
}

int main()
{
    //char str[100] = "This is a sentence";      //与gets同等效果
    char str[200];
    gets(str);
    //scanf("%c", &str);        //不能这么输入,scanf中空格代表输入结束并把回车符留在缓存中;gets可以接收空格并把回车符转换为'\0'
    findLongestWord(str);
    return 0;
}

 用gets不用scanf的原因:scanf不能接收空格遇到空格就代表输入结束,scanf把回车符留在缓存中;gets可以接收空格,把回车符转换为 '\0';gets的返回值为char类型scanf返回值为int类型;gets只能用于输入字符串,而scanf可以输入很多类型的变量

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值