Increment a string with letters?

前端 未结 12 1286
礼貌的吻别
礼貌的吻别 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 13:08

    This will function will do the part of incrementing the string to next sequence

    function increment(str){
    
        var arr = str.split("");
        var c;
        for(var i=arr.length-1; i>=0; i--){
            c = (arr[i].charCodeAt(0)+1)%123;
            arr[i] = String.fromCharCode(c==0?97:c);
            if(c!=0)break;
        }
    return arr.join("");
    }
    

    I was working on another solution to increment by any number and also in reverse direction. The code still has some bugs, but just putting it up here to receive some suggestions. pass in negative numbers to go in reverse direction. Code fails for some edge cases, for eg: when character is 'a' and num is negative number

    function jumpTo(str,num){
    
        var arr = str.split("");
        var c;
        for(var i=arr.length-1; i>=0; i--){
            c = (arr[i].charCodeAt(0)+1)%123;
            c += c==0?97+num-1:num-1;
            arr[i] = String.fromCharCode(c==0?97:c);
            if(c!=0)break;
        }
    return arr.join("");
    }
    

提交回复
热议问题