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

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

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

#include <stdio.h>
#include <string.h>

//计算字符串最后一个单词的长度,单词以空格隔开,字符串长度小于5000。

//实现

int iswordseparator(char c) {
    //暂定单词分割符为空白字符
    if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v') {
        return 1;
    }

    return 0;
}

int getlengthoflastword(char* str) {
    int i = 0, length = 0;

    length = strlen(str);

    //右边空白无视
    while ((length >= 1) && iswordseparator(str[length - 1]) == 1) {
        length--;
    }
    //左边是空白结束
    while ((length >= 1) && iswordseparator(str[length - 1]) != 1) {
        i++;
        length--;
    }

    return i;
}

//测试
char buf[5000];

int main() {

    int length = 0;

    memset(buf, 0, sizeof(buf));

    while (fgets(buf, sizeof(buf), stdin) != NULL) {
        length = getlengthoflastword(buf);
        printf("%d\n", length);
        memset(buf, 0, sizeof(buf));
    }

    return 0;
}

1,读取用fgets,不使用scanf。

2,输出用printf

3,抽取iswordseparator函数,用来区分单词和非单词部分

4,抽取getlengthoflastworld函数,完成计算最后一个单词长度的功能

5,测试用例支持多次输入。读取失败时退出。

全部评论

相关推荐

12-15 12:50
河北工程大学
sta666:我也是这个国际商业化的,三天,一天一面,就通过了,不过我是后端实习生,好好面感觉能过。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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