【问题标题】:How to print each word in a separate line. Each word is capitalized except the first如何在单独的行中打印每个单词。除第一个单词外,每个单词都大写
【发布时间】:2019-07-01 18:51:16
【问题描述】:

我正在尝试创建一个在新行上打印每个单词的函数。给出的参数是一个字符串,其中的单词不是用空格分隔,而是大写,除了第一个单词,即“helloMyNameIsMark”。我有一些可行的方法,但想知道在 javaScript 中是否有更好的方法。

separateWords = (string) => {

  const letters = string.split('');
  let word = "";
  const words = letters.reduce((acc, letter, idx) => {
    if (letter === letter.toUpperCase()) {
      acc.push(word);
      word = "";
      word = word.concat(letter);
    } else if (idx === letters.length - 1) {
      word = word.concat(letter);
      acc.push(word);
    } else {
      word = word.concat(letter)
    }
    return acc
  }, []);
  words.forEach(word => {
    console.log(word)
  })
}

【问题讨论】:

    标签: javascript string algorithm


    【解决方案1】:

    您可以使用正则表达式 [A-Z]replace 每个大写字母加上 \n 前缀

    const separateWords = str => str.replace(/[A-Z]/g, m => '\n' + m)
    
    console.log(separateWords('helloMyNameIsMark'))

    或者您可以在每个大写字母处使用(?=[A-Z])split 的前瞻来获取单词数组。然后循环遍历数组来记录每个单词:

    const separateWords = str => str.split(/(?=[A-Z])/g)
    separateWords('helloMyNameIsMark').forEach(w => console.log(w))

    【讨论】:

      【解决方案2】:

      我会将单词分解成一个数组并将该数组的打印分成两个不同的函数。正则表达式使第一部分比您的reduce 调用更容易。 (但如果您没有看到正则表达式解决方案,reduce 是个好主意。)

      我的版本可能如下所示:

      const separateWords = (str) => str .replace (/([A-Z])/g, " $1") .split (' ')
      
      const printSeparateWords = (str) => separateWords (str) .forEach (word => console.log (word) )
      
      printSeparateWords ("helloMyNameIsMark")

      【讨论】:

        【解决方案3】:

        与阿迪加的答案非常相似,但实际上可以更简单:

        const separateWords = str => str.replace(/[A-Z]/g, '\n$&');
        

        这也将受益于改进的性能(如果大规模使用可能很重要)。

        【讨论】:

          【解决方案4】:

          这是对您声明的要求的更字面解释:打印每个单词换行。

          function separateWords(str){
            let currentWord = '';
          
            for (let chr of str){
              if (chr == chr.toUpperCase()){
                console.log(currentWord);
                currentWord = chr;
              
              } else {
                currentWord += chr;
              }
            }
          
            if (currentWord)
              console.log(currentWord);
          }
          
          separateWords('helloMyNameIsMark');

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-11-09
            • 2016-03-22
            • 2021-05-26
            • 1970-01-01
            • 2020-03-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多