I want to convert an integer into its character equivalent based on the alphabet. For example:
我想基于字母表将一个整数转换成它的等价字符。例如:
0 => a
1 => b
2 => c
3 => d
etc. I could build an array and just look it up when I need it but I'm wondering if there's a built in function to do this for me? All the examples i've found via Google are working with ASCII values and not a characters position in the alphabet.
等等,我可以构建一个数组,当我需要它的时候查找它但是我想知道是否有一个内置函数可以为我做这个?我通过谷歌找到的所有示例都使用ASCII值,而不是字母表中的字符位置。
Cheers. :)
欢呼。:)
11 个解决方案
#1
281
Assuming you want lower case letters:
假设你想要小写字母:
var chr = String.fromCharCode(97 + n); // where n is 0, 1, 2 ...
97 is the ASCII code for lower case 'a'. If you want uppercase letters, replace 97 with 65 (uppercase 'A'). Note that if n > 25
, you will get out of the range of letters.
97是小写a的ASCII码。如果您想要大写字母,请将97替换为65(大写字母“A”)。注意,如果n>25,你就会超出字母的范围。
#2
75
Will be more portable in case of extending to other alphabets:
在扩展至其他字母的情况下,会更方便携带:
char='abcdefghijklmnopqrstuvwxyz'[code]
or, to be more compatible (with our beloved IE):
或者更兼容(与我们心爱的IE):
char='abcdefghijklmnopqrstuvwxyz'.charAt(code);
#3
21
If you don't mind getting multi-character strings back, you can support arbitrary positive indices:
如果您不介意获得多字符的字符串,您可以支持任意的正索引:
function idOf(i) {
return (i >= 26 ? idOf((i / 26 >> 0) - 1) : '') + 'abcdefghijklmnopqrstuvwxyz'[i % 26 >> 0];
}
idOf(0) // a
idOf(1) // b
idOf(25) // z
idOf(26) // aa
idOf(27) // ab
idOf(701) // zz
idOf(702) // aaa
idOf(703) // aab
(Not thoroughly tested for precision errors :)
(未对精度错误进行彻底测试:)
#4
14
A simple answer would be (26 characters):
一个简单的答案是(26个字符):
String.fromCharCode(97+n);
If space is precious you could do the following (20 characters):
如果空间是宝贵的,你可以做以下(20个字符):
(10+n).toString(36);
Think about what you could do with all those extra bytes!
想想你可以用这些多余的字节做什么!
How this works is you convert the number to base 36, so you have the following characters:
它的工作原理是你把数字转换成36,所以你有以下的字符:
0123456789abcdefghijklmnopqrstuvwxyz
^ ^
n n+10
By offsetting by 10 the characters start at a
instead of 0
.
通过10的偏移,字符从a开始而不是0。
Not entirely sure about how fast running the two different examples client-side would compare though.
但是并不完全确定客户端运行这两个不同示例的速度有多快。
#5
6
Javascript's String.fromCharCode(code1, code2, ..., codeN) takes an infinite number of arguments and returns a string of letters whose corresponding ASCII values are code1, code2, ... codeN. Since 97 is 'a' in ASCII, we can adjust for your indexing by adding 97 to your index.
Javascript的String.fromCharCode(code1,code2,…获取无限个参数并返回一个字母串,其对应的ASCII值为code1、code2、……代码数字系统。由于97在ASCII中是“a”,我们可以通过将97添加到索引中来调整索引。
function indexToChar(i) {
return String.fromCharCode(i+97); //97 in ASCII is 'a', so i=0 returns 'a',
// i=1 returns 'b', etc
}
#6
3
Use String.fromCharCode
. This returns a string from a Unicode value, which matches the first 128 characters of ASCII.
使用String.fromCharCode。这将从Unicode值中返回一个字符串,该字符串与ASCII的前128个字符相匹配。
var a = String.fromCharCode(97);
#7
2
There you go: (a-zA-Z)
这是你们要的(a-zA-Z):
function codeToChar( number ) {
if ( number >= 0 && number <= 25 ) // a-z
number = number + 97;
else if ( number >= 26 && number <= 51 ) // A-Z
number = number + (65-26);
else
return false; // range error
return String.fromCharCode( number );
}
input: 0-51, or it will return false (range error);
输入:0-51,否则返回false(范围错误);
OR:
或者:
var codeToChar = function() {
var abc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
return function( code ) {
return abc[code];
};
})();
returns undefined in case of range error. NOTE: the array will be created only once and because of closure it will be available for the the new codeToChar function. I guess it's even faster then the first method (it's just a lookup basically).
返回未定义的范围错误。注意:数组将只创建一次,由于闭包,新的codeToChar函数可以使用它。我猜它比第一个方法还要快(基本上就是查找)。
#8
1
The only problemo with @mikemaccana's great solution is that it uses the binary >> operator which is costly, performance-wise. I suggest this modification to his great work as a slight improvement that your colleagues can perhaps read more easily.
@mikemaccana的唯一问题是它使用了二进制>>操作符,这是昂贵的,性能方面的。我建议对他的伟大工作进行修改,作为一个小小的改进,您的同事也许可以更容易地阅读。
const getColumnName = (i) => {
const previousLetters = (i >= 26 ? getColumnName(Math.floor(i / 26) -1 ) : '');
const lastLetter = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[i % 26];
return previousLetters + lastLetter;
}
Or as a one-liner
或作为一个一行程序
const getColumnName = i => (i >= 26 ? getColumnName(Math.floor(i / 26) -1 ) : '') + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[i % 26];
Example:
例子:
getColumnName(0); // "A"
getColumnName(1); // "B"
getColumnName(25); // "Z"
getColumnName(26); // "AA"
getColumnName(27); // "AB"
getColumnName(80085) // "DNLF"
#9
-1
Assuming you want uppercase case letters:
假设你想要大写字母:
function numberToLetter(num){
var alf={
'0': 'A', '1': 'B', '2': 'C', '3': 'D', '4': 'E', '5': 'F', '6': 'G'
};
if(num.length== 1) return alf[num] || ' ';
return num.split('').map(numberToLetter);
}
Example:
例子:
numberToLetter('023') is ["A", "C", "D"]
数字字母('023')是["A", "C", "D"]
numberToLetter('5') is "F"
numberToLetter(“5”)是“F”
#10
-1
It generates random number and char for phone verification or something else.
它生成随机数和字符用于电话验证或其他东西。
function randomIntFromInterval(min,max)
{
return Math.floor(Math.random()*(max-min+1)+min);
}
function generateRandomVerification(length){
let char;
let sum ="";
for(let i=0;i < length;i++){
if(Math.round(Math.random())){
random = randomIntFromInterval(65,90);
char = String.fromCharCode(random);//65-90
sum = sum + char;
console.log("CHAR: ", char);
}else{
random = randomIntFromInterval(48,57);
char = String.fromCharCode(random);//48-57
sum = sum + char;
console.log("CHAR: ", char);
}
}
alert(sum);
}
generateRandomVerification(5);
Here is link
这里是链接
#11
-6
public static string IntToLetters(int value)
{
string result = string.Empty;
while (--value >= 0)
{
result = (char)('A' + value % 26 ) + result;
value /= 26;
}
return result;
}
To meet the requirement of A being 1 instead of 0, I've added -- to the while loop condition, and removed the value-- from the end of the loop, if anyone wants this to be 0 for their own purposes, you can reverse the changes, or simply add value++; at the beginning of the entire method.
为了满足A为1而不是0的要求,我添加了——在while循环条件下,并从循环的末尾删除了值——如果有人想让这个值为0,那么您可以反转更改,或者简单地添加值++;在整个方法的开始。
#1
281
Assuming you want lower case letters:
假设你想要小写字母:
var chr = String.fromCharCode(97 + n); // where n is 0, 1, 2 ...
97 is the ASCII code for lower case 'a'. If you want uppercase letters, replace 97 with 65 (uppercase 'A'). Note that if n > 25
, you will get out of the range of letters.
97是小写a的ASCII码。如果您想要大写字母,请将97替换为65(大写字母“A”)。注意,如果n>25,你就会超出字母的范围。
#2
75
Will be more portable in case of extending to other alphabets:
在扩展至其他字母的情况下,会更方便携带:
char='abcdefghijklmnopqrstuvwxyz'[code]
or, to be more compatible (with our beloved IE):
或者更兼容(与我们心爱的IE):
char='abcdefghijklmnopqrstuvwxyz'.charAt(code);
#3
21
If you don't mind getting multi-character strings back, you can support arbitrary positive indices:
如果您不介意获得多字符的字符串,您可以支持任意的正索引:
function idOf(i) {
return (i >= 26 ? idOf((i / 26 >> 0) - 1) : '') + 'abcdefghijklmnopqrstuvwxyz'[i % 26 >> 0];
}
idOf(0) // a
idOf(1) // b
idOf(25) // z
idOf(26) // aa
idOf(27) // ab
idOf(701) // zz
idOf(702) // aaa
idOf(703) // aab
(Not thoroughly tested for precision errors :)
(未对精度错误进行彻底测试:)
#4
14
A simple answer would be (26 characters):
一个简单的答案是(26个字符):
String.fromCharCode(97+n);
If space is precious you could do the following (20 characters):
如果空间是宝贵的,你可以做以下(20个字符):
(10+n).toString(36);
Think about what you could do with all those extra bytes!
想想你可以用这些多余的字节做什么!
How this works is you convert the number to base 36, so you have the following characters:
它的工作原理是你把数字转换成36,所以你有以下的字符:
0123456789abcdefghijklmnopqrstuvwxyz
^ ^
n n+10
By offsetting by 10 the characters start at a
instead of 0
.
通过10的偏移,字符从a开始而不是0。
Not entirely sure about how fast running the two different examples client-side would compare though.
但是并不完全确定客户端运行这两个不同示例的速度有多快。
#5
6
Javascript's String.fromCharCode(code1, code2, ..., codeN) takes an infinite number of arguments and returns a string of letters whose corresponding ASCII values are code1, code2, ... codeN. Since 97 is 'a' in ASCII, we can adjust for your indexing by adding 97 to your index.
Javascript的String.fromCharCode(code1,code2,…获取无限个参数并返回一个字母串,其对应的ASCII值为code1、code2、……代码数字系统。由于97在ASCII中是“a”,我们可以通过将97添加到索引中来调整索引。
function indexToChar(i) {
return String.fromCharCode(i+97); //97 in ASCII is 'a', so i=0 returns 'a',
// i=1 returns 'b', etc
}
#6
3
Use String.fromCharCode
. This returns a string from a Unicode value, which matches the first 128 characters of ASCII.
使用String.fromCharCode。这将从Unicode值中返回一个字符串,该字符串与ASCII的前128个字符相匹配。
var a = String.fromCharCode(97);
#7
2
There you go: (a-zA-Z)
这是你们要的(a-zA-Z):
function codeToChar( number ) {
if ( number >= 0 && number <= 25 ) // a-z
number = number + 97;
else if ( number >= 26 && number <= 51 ) // A-Z
number = number + (65-26);
else
return false; // range error
return String.fromCharCode( number );
}
input: 0-51, or it will return false (range error);
输入:0-51,否则返回false(范围错误);
OR:
或者:
var codeToChar = function() {
var abc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
return function( code ) {
return abc[code];
};
})();
returns undefined in case of range error. NOTE: the array will be created only once and because of closure it will be available for the the new codeToChar function. I guess it's even faster then the first method (it's just a lookup basically).
返回未定义的范围错误。注意:数组将只创建一次,由于闭包,新的codeToChar函数可以使用它。我猜它比第一个方法还要快(基本上就是查找)。
#8
1
The only problemo with @mikemaccana's great solution is that it uses the binary >> operator which is costly, performance-wise. I suggest this modification to his great work as a slight improvement that your colleagues can perhaps read more easily.
@mikemaccana的唯一问题是它使用了二进制>>操作符,这是昂贵的,性能方面的。我建议对他的伟大工作进行修改,作为一个小小的改进,您的同事也许可以更容易地阅读。
const getColumnName = (i) => {
const previousLetters = (i >= 26 ? getColumnName(Math.floor(i / 26) -1 ) : '');
const lastLetter = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[i % 26];
return previousLetters + lastLetter;
}
Or as a one-liner
或作为一个一行程序
const getColumnName = i => (i >= 26 ? getColumnName(Math.floor(i / 26) -1 ) : '') + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[i % 26];
Example:
例子:
getColumnName(0); // "A"
getColumnName(1); // "B"
getColumnName(25); // "Z"
getColumnName(26); // "AA"
getColumnName(27); // "AB"
getColumnName(80085) // "DNLF"
#9
-1
Assuming you want uppercase case letters:
假设你想要大写字母:
function numberToLetter(num){
var alf={
'0': 'A', '1': 'B', '2': 'C', '3': 'D', '4': 'E', '5': 'F', '6': 'G'
};
if(num.length== 1) return alf[num] || ' ';
return num.split('').map(numberToLetter);
}
Example:
例子:
numberToLetter('023') is ["A", "C", "D"]
数字字母('023')是["A", "C", "D"]
numberToLetter('5') is "F"
numberToLetter(“5”)是“F”
#10
-1
It generates random number and char for phone verification or something else.
它生成随机数和字符用于电话验证或其他东西。
function randomIntFromInterval(min,max)
{
return Math.floor(Math.random()*(max-min+1)+min);
}
function generateRandomVerification(length){
let char;
let sum ="";
for(let i=0;i < length;i++){
if(Math.round(Math.random())){
random = randomIntFromInterval(65,90);
char = String.fromCharCode(random);//65-90
sum = sum + char;
console.log("CHAR: ", char);
}else{
random = randomIntFromInterval(48,57);
char = String.fromCharCode(random);//48-57
sum = sum + char;
console.log("CHAR: ", char);
}
}
alert(sum);
}
generateRandomVerification(5);
Here is link
这里是链接
#11
-6
public static string IntToLetters(int value)
{
string result = string.Empty;
while (--value >= 0)
{
result = (char)('A' + value % 26 ) + result;
value /= 26;
}
return result;
}
To meet the requirement of A being 1 instead of 0, I've added -- to the while loop condition, and removed the value-- from the end of the loop, if anyone wants this to be 0 for their own purposes, you can reverse the changes, or simply add value++; at the beginning of the entire method.
为了满足A为1而不是0的要求,我添加了——在while循环条件下,并从循环的末尾删除了值——如果有人想让这个值为0,那么您可以反转更改,或者简单地添加值++;在整个方法的开始。