【问题标题】:Replace a letter with its alphabet position用字母位置替换字母
【发布时间】:2017-05-16 13:44:16
【问题描述】:

当我开始时,这对我来说看起来相当简单,但由于某种原因,我每次尝试在 codewars 上运行结果时都会得到一个空数组。希望您能帮我找出问题所在。

function alphabetPosition(text) {
  text.split(' ').join('');
  var chari = "";
  var arr = [];
  var alphabet = "abcdefghijklmnopqrstuvwxyz".split('');
  for(var i = 0; i < text.len; i++){
    chari = text.charAt(i).toLowerCase();
    if(alphabet.indexOf(chari) > -1){
      arr.push(alphabet.indexOf(chari));
    }
  }
  return arr;
}
console.log(alphabetPosition("Hello World"));

我的想法是从参数中获取文本,然后去掉空格。我为我的空数组创建了一个变量,并创建了一个以后可以搜索的字母字符串。在 for 循环中,我将每个字符设为小写,如果在字母字符串中找到该字符,则将其位置推入数组 (arr)。感谢您的宝贵时间。

【问题讨论】:

  • text.len 这不应该是text.length吗?
  • 感谢大家的所有回答,谢谢。 len 的事情导致了数组问题。也许我正在考虑使用 Python。
  • @MlowBunjay - 应始终检查浏览器控制台是否有错误消息。 *.com/questions/1648582/…

标签: javascript arrays string


【解决方案1】:

您需要String#length 属性

text.length

而不是text.len

function alphabetPosition(text) {
    var chari,
        arr = [],
        alphabet = "abcdefghijklmnopqrstuvwxyz",
        i;

    for (var i = 0; i < text.length; i++){
        chari = text[i].toLowerCase();
        if (alphabet.indexOf(chari) !== -1){
            arr.push(alphabet.indexOf(chari));
        }
    }
    return arr;
}
console.log(alphabetPosition("Hello World!!1"));

使用 ES6 的解决方案

function alphabetPosition(text) {
    return [...text].map(a => parseInt(a, 36) - 10).filter(a => a >= 0);
}
console.log(alphabetPosition("Hello World!!1"));

【讨论】:

  • 添加 ES6 解决方案很不错。我更新为基于 1 的数组结果,因为这是公认的解决方案所基于的。
  • @KraangPrime,我认为,结果应该是从零开始的。
  • 我同意,这也是我解决问题的方式(基于 0 才有意义)。一旦我看到接受的解决方案是基于 1 的,就加倍考虑我的解决方案。但是无论它在什么数组基础中,ES6 都非常热门:)
  • @NinaScholz 很好的答案。 (a,36) 有什么作用?
  • @MikiBelavista,它需要一个以 36 为底的值才能将其转换为字母。
【解决方案2】:

首先:删除空间
第二:将每个字符与其字母等级进行映射
第三:测试字符串Happy new year

var alphabet = "abcdefghijklmnopqrstuvwxyz".split('');
var alphabetPosition = text => 
  text.split('').map(x => alphabet.indexOf(x) + 1);
console.log(alphabetPosition("happy new year"));

【讨论】:

  • 几点注意事项:您可能希望在映射之前将文本字符串小写; indexOf 从 0 开始,通常字母表中的字母位置从 1 开始。除此之外,不错的代码
  • @VladimirM :是的,这只是一个快速的答案,但你是对的。还可以使用短正则表达式测试字符串中的 char 是否是非字母的
  • 我更新为基于 1 的数组结果,因为这是公认的解决方案所基于的。也摆脱了Split(' ').Join(''),因为无论如何都会跳过所有非字母字符。
【解决方案3】:

len 更改为length

(var i = 0; i < text.len; i++)
// change to
(var i = 0; i < text.length; i++)

【讨论】:

    【解决方案4】:

    您可以通过使用 acii 代码使其变得更加简单。因为a = ascii 代码 97、b = 98 等等。还有一个 javascript 函数 String.charCodeAt( n ) 在特定函数处返回 ascii 代码。您只需更改大写字母的偏移量(如果您想支持它们)。

    function alphabetPosition( text ) {
    	var positions = [];
    	for ( var i = 0; i < text.length; i++ ) {
    		var charCode = text.charCodeAt( i );
    		if ( charCode >= 97 && charCode <= 122 ) {
    			positions.push( charCode - 96 );
    		} else if ( charCode >= 65 && charCode <= 90 ) { // get rid of this if you don't care about capitals
    			positions.push( charCode - 64 );
    		}
    	}
    	return positions;
    }
    
    var positions = alphabetPosition( 'Hello World' );
    console.log(positions);

    检查这个工作fiddle

    【讨论】:

      【解决方案5】:

      你也可以使用.charCodeAt函数:

      function alphabetPosition(text) {
          start = "a".charCodeAt(0);
          end = "z".charCodeAt(0);
          res = [];
          for (var i = 0; i < text.length; i++) {
              index = text.charAt(i).toLowerCase().charCodeAt(0);
              if (index >= start && index <= end) {
                  res.push(index - start +1); // +1 assuming a is 1 instead of 0
              } else {
                  res.push(0); // Or do w/e you like with non-characters
              }
          }
          return res;
      }
      console.log(alphabetPosition("Hello World"));

      【讨论】:

        【解决方案6】:

        Kata 使用此代码。试试这个:

        function alphabetPosition(text) {
          var result = "";
          for (var i = 0; i < text.length; i++) {
            var code = text.toUpperCase().charCodeAt(i)
            if (code > 64 && code < 91) result += (code - 64) + " ";
          }
        
          return result.slice(0, result.length - 1);
        }
        console.log(alphabetPosition("The sunset sets at twelve o' clock."));

        【讨论】:

          【解决方案7】:

          你可以这样做;

          var alpha = [].reduce.call("abcdefghijklmnopqrstuvwxyz0123456789 .,!",(p,c,i) => (p[c] = i,p),{}),
                str = "Happy 2017 whatever..!",
              coded = [].map.call(str, c => alpha[c.toLowerCase()]);
          console.log(coded);

          【讨论】:

            【解决方案8】:

            此示例将基于基于 0 的数组返回,并使用带有过滤器的 lambda 表达式。我回收了通过拆分传递给方法的文本创建的原始字节数组。

            function alphabetPosition(text) {
              var bytes = text.split('');
              var alphabet = "abcdefghijklmnopqrstuvwxyz".split('');
              for (var i = 0, len = text.length; i < len; i++) {
            	bytes[i] = alphabet.indexOf(bytes[i].toLowerCase());
              }
              return bytes.filter(n => { if(n > -1) return n; } ).join(' ');
            }
            console.log(alphabetPosition("Hello World"));

            对于基于 1 的数组结果 Kata Codewars Friendly

            function alphabetPosition(text) {
              var bytes = text.split('');
              var alphabet = "abcdefghijklmnopqrstuvwxyz".split('');
              for (var i = 0, len = text.length; i < len; i++) {
            	bytes[i] = alphabet.indexOf(bytes[i].toLowerCase()) + 1;
              }
              return bytes.filter(n => { if(n > 0) return n; } ).join(' ');
            }
            console.log(alphabetPosition("Hello World"));

            【讨论】:

              【解决方案9】:

              下面是一个短得多的版本,其功能相同:

              function alphabetPosition(text){
                return text.split('').map(function(character){ return character.charCodeAt(0) - 'a'.charCodeAt(0) + 1; })
              }
              
              console.log(alphabetPosition("Hello World"));
              

              【讨论】:

                【解决方案10】:

                这是我在 CodeWars 上的解决方案。完美运行;)

                let alphabetPosition = (text) => {
                  let str = Array.from(text.toLowerCase().replace(/[^a-z]/g,''));
                  let arr = [];
                  for (let i = 0; i < str.length; i++) {
                     arr.push(str[i].charCodeAt() - 96);
                  }
                    return arr.join(' ');
                }
                

                【讨论】:

                  【解决方案11】:
                  function alphabetPosition(text) {
                    const words = text.toLowerCase().replace(/[^a-z]/g,"");
                    return [...words].map(v=> v.charCodeAt() - 96);
                  }
                  

                  首先,我们使用text.toLowerCase() 将文本转换为小写以去除大写字母,然后使用.replace(/[^a-z]/g,"") 将所有非a-z 字符替换为空。

                  下一步是使用[...words] 将字符串展开成一个数组,然后对其进行映射以获取每个 a-z 字符的 ascii 字符代码。

                  由于 a = 97 和 b = 98 等,我们将减去 96,从而得到 a = 1 和 b = 2 等(字母在字母表中的位置)

                  【讨论】:

                    【解决方案12】:

                    我的回答

                    function alphabetPosition(text) {
                      if (text.match(/[a-z]/gi)) {                                        // if text is not emtpty
                        let justAlphabet = text.match(/[a-z]/gi).join("").toLowerCase(); //first extract characters other than letters
                        let alphabet = "abcdefghijklmnopqrstuvwxyz";
                        let a = [];                                                    // Create an empty array
                        for (let i = 0; i < justAlphabet.length; i++) {
                          a.push(alphabet.indexOf(justAlphabet[i]) + 1);             //and characters index number push in this array
                        }
                        return a.join(" ");
                      } else {
                        return "";                                               
                      }
                    }
                    
                    console.log(alphabetPosition("The sunset sets at twelve o' clock."));

                    【讨论】:

                    • 请添加一些解释。为什么您认为您提出的解决方案可能对 OP 有所帮助。
                    【解决方案13】:

                    这个应该可以的

                    const lineNumberHandler = (arr) => {
                        const alphabet = 'abcdefghijklmnopqrstuwxyz';
                        return arr.map((el) => `${alphabet.indexOf(el) + 1}:${el}`);
                    }
                    

                    【讨论】:

                      【解决方案14】:

                      这也可以解决问题:

                       function alphabetPosition(text) {
                                  const alphabet = 'abcdefghijklmnopqrstuvwxyz'
                                  const textWithoutSpaces = text.replace(/\s/g, '');
                                  const numbers = Array.from(textWithoutSpaces).map((letter) => {
                                      const lowerCaseLetter = letter.toLowerCase();
                                      const charI = alphabet.indexOf(lowerCaseLetter)+1
                                      if(charI) return charI
                                      return null
                                  })
                                  const withoutEmptyValues = numbers.filter(Boolean)
                                  return withoutEmptyValues.join(' ')
                              }
                      

                      【讨论】:

                        【解决方案15】:

                        function alphabetPosition(text) {
                          var result = "";
                          for (var i = 0; i < text.length; i++) {
                            var code = text.toUpperCase().charCodeAt(i)
                            if (code > 64 && code < 91) result += (code - 64) + " ";
                          }
                        
                          return result.slice(0, result.length - 1);
                        }
                        console.log(alphabetPosition("The sunset sets at twelve o' clock."));

                        【讨论】:

                          【解决方案16】:
                          function alphabetPosition(text) {
                            const letters = text.split('')
                            const result = letters.map((l, ix) => {
                              const code = l.toUpperCase().charCodeAt() - 64
                              if (l.length && code > 0 && code <= 26) {
                                return code  
                              }
                            })
                            return result.join(' ').replace(/\s+/g, ' ').trim()
                          }
                          

                          我喜欢做“单行责任”,所以在每一行中你只能找到一个动作。

                          回车,删除所有的倍数空格。

                          【讨论】: