Increment a string with letters?

前端 未结 12 1274
礼貌的吻别
礼貌的吻别 2021-02-08 12:35

I need to increment a string from.. let\'s say aaa to zzz and write every incrementation in the console (is incrementation even a word?). It would go s

12条回答
  •  有刺的猬
    2021-02-08 12:53

    Took a bit of algorithmic approach. This function takes initial string as an argument, increments next possible char in alphabet and at last returns the result.

    function generate(str)
    {
      var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
      var chars = [];
      for(var i = 0; i < str.length; i++)
      {
        chars.push(alphabet.indexOf(str[i]));
      }
      for(var i = chars.length - 1; i >= 0 ; i--)
      {
        var tmp = chars[i];
        if(tmp >= 0 && tmp < 25) {
          chars[i]++;
          break;
        }
        else{chars[i] = 0;}
      }
      var newstr = '';
      for(var i = 0; i < chars.length; i++)
      {
        newstr += alphabet[chars[i]];
      }
      return newstr;
    } 
    

    Here is the loop helper function which accepts the initial string to loop through and generate all combinations.

    function loop(init){
      var temp = init;
      document.write(init + "
    "); while(true) { temp = generate(temp); if(temp == init) break; document.write(temp + "
    "); } }

    Usage: loop("aaa");

    CODEPEN

提交回复
热议问题