用字母增加一个字符串? [英] Increment a string with letters?
问题描述
我需要从..增加一个字符串...让我们说 aaa
到 zzz
并在控制台中写下每个增量(甚至一个字都增加?)。它会是这样的:
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 something like this:
aaa
aab
aac
...
aaz
aba
abb
abc
...
abz
aca
acb
依此类推。到目前为止,我通过这样做增加了一个字母:
And so on. So far I have incremented a single letter by doing this:
String.prototype.replaceAt = function(index, character) {
return this.substr(0, index) + character + this.substr(index+character.length);
}
string = "aaa";
string = string.replaceAt(2, String.fromCharCode(string.charCodeAt(2) + 1));
//string == "aab"
然而,我迷路了当最后的字母是 z
时,它应该增加字母2(索引1)并将最后一个字母重置为 a
。
However, I am lost when it comes to the final letter being z
and it should then increment letter 2 (index 1) and reset the last letter to be a
.
有没有人拥有或知道这个智能解决方案?谢谢!
Does anyone have or know a smart solution to this? Thanks!
推荐答案
将字符串视为基数为36的数字。
Treat the string like it's a base 36 number.
将其转换为十进制,加1,转换回基数36,并用字母'a'替换任何零:
Convert it to decimal, add 1, convert back to base 36, and replace any zeroes with the letter 'a':
var str= 'aaa',
s= str;
while(str!=='zzz') {
str= ((parseInt(str, 36)+1).toString(36)).replace(/0/g,'a');
s+= ' '+str;
}
document.body.innerHTML= s;
这篇关于用字母增加一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!