题解 | #字符串最后一个单词的长度#

字符串最后一个单词的长度

https://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da

不愧是最难的C,光是输入就可以深入研究了
#include <stdio.h>
#include <string.h>
#include <malloc.h>

const int INPUT_MAX_LEN = 5000;

int main()
{
    // 创建长度为INPUT_MAX_LEN的字符数组
    char* str = (char*)malloc(sizeof(char)*INPUT_MAX_LEN);
    // 获取1行输入,stdin声明在stdio.h中,表示从键盘标准输入
    while (fgets(str,INPUT_MAX_LEN,stdin))
    {
        int len = 0;
        int lastWordLen = 0;

        // 换行符'\n'替换成'\0'
        char* p = strchr(str,'\n');
        if(p!=NULL)
        {
            *p = '\0';
        }

        len = (int) strlen(str);

        // 没空格的情况
        if(strchr(str,' ') == NULL)
        {
            printf("%d\n", len);
            continue;
        }
        // 有的情况
        for (int i = len-1; i > 0; i--)
        {
            if(str[i] == ' ')
            {
                break;
            }
            lastWordLen++;
        }

        printf("%d\n", lastWordLen);
    }
}


#牛客OJ##华为笔试#
全部评论

相关推荐

06-10 23:36
已编辑
首都经济贸易大学 C++
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务