将整数转换为其等效字符,其中 0 => a, 1 =>乙等

发布于 2024-09-07 18:10:15 字数 195 浏览 5 评论 0原文

我想根据字母表将整数转换为其等效字符。例如:

0 => a
1 => b
2 => c
3 => d

等等。我可以构建一个数组,然后在需要时查找它,但我想知道是否有一个内置函数可以为我执行此操作。我通过 Google 找到的所有示例都使用 ASCII 值,而不是字符在字母表中的位置。

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 character’s position in the alphabet.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

写下不归期 2024-09-14 18:10:15

假设您想要小写字母:

var chr = String.fromCharCode(97 + n); // where n is 0, 1, 2 ...

97 是小写“a”的 ASCII 代码。如果您需要大写字母,请将 97 替换为 65(大写“A”)。请注意,如果 n > 25,您将超出字母范围。

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.

放飞的风筝 2024-09-14 18:10:15

如果扩展到其他字母表,将更加便携:

char='abcdefghijklmnopqrstuvwxyz'[code]

或者,更加兼容(与我们心爱的 IE):

char='abcdefghijklmnopqrstuvwxyz'.charAt(code);

Will be more portable in case of extending to other alphabets:

char='abcdefghijklmnopqrstuvwxyz'[code]

or, to be more compatible (with our beloved IE):

char='abcdefghijklmnopqrstuvwxyz'.charAt(code);
无法回应 2024-09-14 18:10:15

如果您不介意返回多字符字符串,则可以支持任意正索引:(

function idOf(i) {
  return (
    (i >= 26 ? idOf(((i / 26) >> 0) - 1) : "") +
    "abcdefghijklmnopqrstuvwxyz"[i % 26 >> 0]
  );
}

[0, 1, 25, 26, 27, 701, 702, 703].map(idOf);
// ['a', 'b', 'z', 'aa', 'ab', 'zz', 'aaa', 'aab']

未彻底测试精度错误:)

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]
  );
}

[0, 1, 25, 26, 27, 701, 702, 703].map(idOf);
// ['a', 'b', 'z', 'aa', 'ab', 'zz', 'aaa', 'aab']

(Not thoroughly tested for precision errors :)

清风挽心 2024-09-14 18:10:15

一个简单的答案是(26 个字符):

String.fromCharCode(97+n);

如果空间很宝贵,您可以执行以下操作(20 个字符):

(10+n).toString(36);

想想您可以用所有这些额外的字节做什么!

其工作原理是将数字转换为基数 36,这样就得到了以下字符:

0123456789abcdefghijklmnopqrstuvwxyz
^         ^
n        n+10

通过偏移 10,字符从 a 开始,而不是 0

但不完全确定客户端运行两个不同示例的速度有多快。

A simple answer would be (26 characters):

String.fromCharCode(97+n);

If space is precious you could do the following (20 characters):

(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:

0123456789abcdefghijklmnopqrstuvwxyz
^         ^
n        n+10

By offsetting by 10 the characters start at a instead of 0.

Not entirely sure about how fast running the two different examples client-side would compare though.

余生再见 2024-09-14 18:10:15

我不喜欢所有使用 9736 等幻数的解决方案。

const A = 'A'.charCodeAt(0);

let numberToCharacter = number => String.fromCharCode(A + number);

let characterToNumber = character => character.charCodeAt(0) - A;

假定字母为大写,“A”从 0 开始。

I don't like all the solutions that use magic numbers like 97 or 36.

const A = 'A'.charCodeAt(0);

let numberToCharacter = number => String.fromCharCode(A + number);

let characterToNumber = character => character.charCodeAt(0) - A;

this assumes uppercase letters and starts 'A' at 0.

逆流 2024-09-14 18:10:15

Javascript 的 String.fromCharCode(code1, code2, ..., codeN) 接受无限数量的参数并返回一个字母字符串,其对应的 ASCII 值为 code1, code2, ... codeN。由于 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
}

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.

function indexToChar(i) {
  return String.fromCharCode(i+97); //97 in ASCII is 'a', so i=0 returns 'a', 
                                    // i=1 returns 'b', etc
}
度的依靠╰つ 2024-09-14 18:10:15

使用String.fromCharCode。这会从 Unicode 值返回一个字符串,该字符串与 ASCII 的前 128 个字符匹配。

var a = String.fromCharCode(97);

Use String.fromCharCode. This returns a string from a Unicode value, which matches the first 128 characters of ASCII.

var a = String.fromCharCode(97);
冷情妓 2024-09-14 18:10:15

就这样:(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 );
}

输入:0-51,否则会返回false(范围错误);

OR:

var codeToChar = function() {
  var abc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
  return function( code ) {
    return abc[code];
  };
})();

如果范围错误,则返回未定义。
注意:该数组只会创建一次,并且由于闭包,它将可用于新的 codeToChar 函数。我想它比第一种方法更快(基本上只是一个查找)。

There you go: (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);

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).

烟雨凡馨 2024-09-14 18:10:15

尝试

(n+10).toString(36)

chr = n=>(n+10).toString(36);

for(i=0; i<26; i++) console.log(`${i} => ${ chr(i) }`);

Try

(n+10).toString(36)

chr = n=>(n+10).toString(36);

for(i=0; i<26; i++) console.log(`${i} => ${ chr(i) }`);

獨角戲 2024-09-14 18:10:15

@mikemaccana 的出色解决方案的唯一问题是它使用二进制 >>运营商的成本高昂,性能明智。我建议对他的伟大著作进行修改,作为一个小小的改进,这样你的同事也许可以更容易地阅读。

const getColumnName = (i) => {
     const previousLetters = (i >= 26 ? getColumnName(Math.floor(i / 26) -1 ) : '');
     const lastLetter = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[i % 26]; 
     return previousLetters + lastLetter;
}

或者作为单行

const getColumnName = i => (i >= 26 ? getColumnName(Math.floor(i / 26) -1 ) : '') + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[i % 26];

示例:

getColumnName(0); // "A"
getColumnName(1); // "B"
getColumnName(25); // "Z"
getColumnName(26); // "AA"
getColumnName(27); // "AB"
getColumnName(80085) // "DNLF"

The only problem 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.

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"
青柠芒果 2024-09-14 18:10:15

如果您正在寻找 TypeScript 工作函数,请按照

public numericValue = (alphaChar: any) => alphaChar.toUpperCase().charCodeAt(0) - 64;

public alphaValue = (numericDigit: any) => 
   String.fromCharCode(64 + numericDigit) : '';

您可以进行多项检查,例如 (numericDigit >= 1 && numericDigit <= 26) ? 根据要求在函数体内。

If you are looking for TypeScript working functions then follow

public numericValue = (alphaChar: any) => alphaChar.toUpperCase().charCodeAt(0) - 64;

public alphaValue = (numericDigit: any) => 
   String.fromCharCode(64 + numericDigit) : '';

You can make several checks like (numericDigit >= 1 && numericDigit <= 26) ? inside function body as per the requirements.

烟─花易冷 2024-09-14 18:10:15

假设您想要大写字母:

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);
    }

示例:

numberToLetter('023')["A", "C", "D"]

numberToLetter('5 ')“F”

数字转字母函数

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"]

numberToLetter('5') is "F"

number to letter function

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文