如何在Javascript中将字母递增到无穷大

时间:2019-03-06 11:57:02

标签: javascript

一个返回下一个字符的函数。例如,给定A,下一个字母应为B。

假设您要使用字母命名项目列表...您将以A,B ... Z开头。但是在Z之后,您想以AA,AB,AC ... AZ开头。哪个会进入BA,BB,BC ... BZ。当您到达ZZ时,您要以AAA开头

A -> B
B -> C
Z -> AA
AA -> AB
AB -> AC
AZ -> BA
BA -> BB
ZZ -> AAA

我最初的工作是获得下一个字符直到Z

的功能。

const nextLetter = (char) => {
 return char === 'Z' ? 'A': String.fromCharCode(char.charCodeAt(0) + 1);
}

console.log(nextLetter('A'))
console.log(nextLetter('G'))
console.log(nextLetter('Z'))

但是后来我想出了一个我想与世界分享的解决方案,可以改善它,也可以提高效率。

Link to the first solution

3 个答案:

答案 0 :(得分:3)

函数incrementChar()将始终返回下一个字母或字母字符串。

const nextLetter = (char) => {
 return char === 'Z' ? 'A': String.fromCharCode(char.charCodeAt(0) + 1);
}

let newCharArray = [];

const incrementChar = (l) => {
  const lastChar = l[l.length - 1]
  const remString = l.slice(0, l.length - 1)
  const newChar = lastChar === undefined ? 'A' : nextLetter(lastChar);
  newCharArray.unshift(newChar)

  if (lastChar === 'Z') {
    return incrementChar(remString)
  } 
  const batchString = remString + [...newCharArray].join('')
  newCharArray = []
  return batchString;
}

console.log(incrementChar(''))
console.log(incrementChar('A'))
console.log(incrementChar('AZ'))
console.log(incrementChar('BZ'))
console.log(incrementChar('ZZ'))
console.log(incrementChar('CAZ'))
console.log(incrementChar('DZZ'))
console.log(incrementChar('ZZZZ'))

答案 1 :(得分:1)

您可以使用两个专用函数来获取数字值或字母值。

function getValue(s) {
    return s.split('').reduce((r, a) => r * 26 + parseInt(a, 36) - 9, 0) - 1;
}

function setValue(n) {
    var result = '';
    do {
        result = (n % 26 + 10).toString(36) + result;
        n = Math.floor(n / 26) - 1;
    } while (n >= 0)
    return result.toUpperCase();
}

function incrementChar(string) {
    return setValue(getValue(string) + 1);
}

console.log(incrementChar(''));
console.log(incrementChar('A'));
console.log(incrementChar('AZ'));
console.log(incrementChar('BZ'));
console.log(incrementChar('ZZ'));
console.log(incrementChar('CAZ'));
console.log(incrementChar('DZZ'));
console.log(incrementChar('ZZZZ'));
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)

这是我在Javascript中将增量字母增加到无穷大的函数(仅限大写)

function getNextStringId(str) {
    let index = str.length-1;
    let baseCode= str.charCodeAt(index);
    do{
        baseCode= str.charCodeAt(index);
        let strArr= str.split("");
        if(strArr[index] == "Z"){
            strArr[index] = "A";
            if(index==0){
                strArr.unshift("A");
            }
        }
        else{
            strArr[index]= String.fromCharCode(baseCode + 1);
        }
        str= strArr.join("");
        index--;
    } while(baseCode == 90)
    return str;
}


getNextStringId("A") // B
getNextStringId("Z") // AA
getNextStringId("ABZZ") // ACAA