简体   繁体   English

如何将一串数字转换为字符

[英]how to convert a string of numbers to a char

Excuse me if this has been answered previously, but I can't seem to find an answer.对不起,如果之前已经回答过这个问题,但我似乎找不到答案。

How do I convert a string of numbers (eg "50") into a single char with an ASCII value of the same number, in this case '2'.如何将一串数字(例如“50”)转换为具有相同数字的 ASCII 值的单个字符,在本例中为“2”。 Is there a way to do this conversion?有没有办法进行这种转换?

Alternatively, could I do the same by converting the string to an int first?或者,我可以通过先将字符串转换为 int 来做同样的事情吗?

Here for some languages:这里有一些语言:

C/C++ C/C++

int i = 65;
char c = i;
printf("%c", c); // prints A

JS JS

var c = String.fromCharCode(66);
console.log(c); // prints B

C#/Java C#/Java

char c = (char)67;
// For Java use System.out.println(c)
Console.WriteLine(c) // prints C

Python Python

c = chr(68) # for Python 2 use c = str(unichr(68))
print(c) # Prints D
String s = "50";
try {
    char c = (char) Integer.valueOf(s);
    ... c
} catch (NumberFormatException e) {
    ...
}

With catching the NumberFormatException and checking the integer range the code might be made rock-solid.通过捕获 NumberFormatException 并检查整数范围,代码可能会变得坚如磐​​石。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM