Increment a string with letters?

前端 未结 12 1291
礼貌的吻别
礼貌的吻别 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:14

    I used your code and added a few new functions.

    String.prototype.replaceAt = function(index, character) {
        return this.substr(0, index) + character + this.substr(index+character.length);
    }
    
    String.prototype.incrementAt = function(index) {
        var newChar = String.fromCharCode(this.charCodeAt(index) + 1); // Get the next letter that this char will be
        if (newChar == "{") { // If it overflows
            return this.incrementAt(index - 1).replaceAt(index, "a"); // Then, increment the next character and replace current char with 'a'
        }
        return this.replaceAt(index, newChar); // Replace this char with next letter
    }
    
    String.prototype.increment = function() {
        return this.incrementAt(this.length - 1); // Starts the recursive function from the right
    }
    
    console.log("aaa".increment()); // Logs "aab"
    console.log("aaz".increment()); // Logs "aba"
    console.log("aba".increment()); // Logs "abb"
    console.log("azz".increment()); // Logs "baa"
    

    This incrementAt function is recursive and increments the character it is currently on. If in the process it overflows (the character becomes { which is after z) it calls incrementAt on the letter before the one it is on.

    The one problem with this code is if you try to increment zzz you get aaaz. This is because it is trying to increment the -1th character which is the last one. If I get time later I'll update my answer with a fix.

    Note that this solution will work if you have a different length string to start off. For example, "aaaa" will count up to "zzzz" just fine.

提交回复
热议问题