【问题标题】:Print out last character of all words in a string打印出字符串中所有单词的最后一个字符
【发布时间】:2015-01-22 02:01:22
【问题描述】:

有哪些简洁的方法可以打印出字符串中所有单词的最后一个字符。例如,像“laugh ride lol hall bozo”这样的短语 --> “hello” 和 “dog polo boo sudd noob smiley ride” --> goodbye。

这些行将返回“1”且未定义。非常感谢任何帮助。

var decrypt = function (message) {
    var solution = [];
    for (var i = 0; i < message.length; i++) {
        if(message.charAt(i)===" ") {
            return solution.push(message.charAt(i-1));
        };
    };
};

var resulta = decrypt("laugh ride lol hall bozo ")
console.log(resulta); // logs "hello"

var resultb = decrypt("dog polo boo sudd noob smiley ride ")
console.log(resultb); // logs "goodbye"

【问题讨论】:

  • return 退出函数。

标签: javascript arrays string for-loop charat


【解决方案1】:

不要在循环内return,只需将字符附加到结果中即可。循环完成后,返回你想要的。由于您显然想返回一个字符串,因此不需要数组。

var decrypt = function (message) {
    var solution = '';
    for (var i = 0; i < message.length; i++) {
        if(message.charAt(i)===" ") {
            solution += message.charAt(i-1);
        };
    };
    return solution;
};

var resulta = decrypt("laugh ride lol hall bozo ")
console.log(resulta); // logs "hello"

var resultb = decrypt("dog polo boo sudd noob smiley ride ")
console.log(resultb); // logs "goodbye"

【讨论】:

  • 效果很好,谢谢 Barmar。什么是打印字符串中最后一个字符的更优化方法,以便不必在末尾插入额外的“”?插入排序会泄露“解密的消息”..
  • 你总是可以在你的函数中添加一个额外的空间。
  • @Henry 我会使用split(' ') 将字符串拆分为单词。然后循环遍历,获取每个字符的最后一个字符。这比在字符串中逐个字符好。
【解决方案2】:

假设单词用空格分隔,你可以在一行中完成:

var decrypt = function (message) {
  return (message+" ").match(/\w\s/g).join("").replace(/\s/g,"");
}

正则表达式/\w\s/g 将匹配一个单词字符后跟一个空格。 .match() 方法将返回所有此类匹配的数组。 .join() 将数组元素连接成一个字符串。然后.replace() 将从该字符串中删除空格。

请注意,我使用(message+" ") 为输入字符串添加一个额外的空格,以防万一它最后没有空格。

另外,我展示的代码不允许字符串中没有任何“单词字符”。如果你想测试,你需要两行:

var decrypt = function (message) {
  var m = (message+" ").match(/\w\s/g);
  return m ? m.join("").replace(/\s/g,"") : "";
  //include default value for non match here^^
}

【讨论】:

  • 不客气。 (如果您不介意难以阅读代码,您可以在一行中执行第二个版本,如下所示:return ((message+" ").match(/\w\s/g)||[]).join("").replace(/\s/g,"");
【解决方案3】:

另一个干净的解决方案是

var decrypt = function (message) { 
    return message.split(' ')
        .map(function(word) { return word.slice(-1); })
        .join('');
}

这依赖于 Array.prototype.map,它是在 ES5 中添加的,支持所有现代浏览器 (http://kangax.github.io/compat-table/es5/#Array.prototype.map)。

【讨论】:

    【解决方案4】:

    考虑到您只关心每个单词的最后一个字符,我会反向循环遍历字符串。这使您还可以打印字符串中的最后一个字符,而无需在编码消息的末尾附加空格。

    function decrypt(message) {
        var c, secret = '', lastSpace = true;
        for (var i = (message || '').length - 1; i >= 0; i--, lastSpace = c === ' ') {
            c = message.charAt(i);
            if (lastSpace) secret = c + secret;
        }
        return secret;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-28
      • 1970-01-01
      • 2022-11-13
      • 2013-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-20
      相关资源
      最近更新 更多