HJ1 字符串最后一个单词的长度 2022-03-11 周五

2022-03-11  本文已影响0人  勇往直前888

题目

计算字符串最后一个单词的长度,单词以空格隔开,字符串长度小于5000。(注:字符串末尾不以空格为结尾)

题解链接

思路

const line = readline();

function getLastWordLength(str) {
    let i = str.length - 1;

    while (i > -1) {
        if (str[i] === ' ') break;
        i -= 1;
    }

    return str.length - 1 - i;
}

console.log(getLastWordLength(line));
function getLastWordLength(str) {
    const array = str.split(" ");
    
    const lastWord = array.pop();
    
    return lastWord.length;
}

const line = readline();
console.log(getLastWordLength(line));
function getLastWordLength(str) {
    const index = str.lastIndexOf(" ");
    
    const lastWord = str.substring(index + 1);
    
    return lastWord.length;
}

const line = readline();
console.log(getLastWordLength(line));

感想

JS语法参考

菜鸟教程

W3C

上一篇 下一篇

猜你喜欢

热点阅读