Reputation: 31
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 (e.g "50") into a single char with an ASCII value of the same number, in this case '2'. Is there a way to do this conversion?
Alternatively, could I do the same by converting the string to an int first?
Upvotes: 1
Views: 2212
Reputation: 109613
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.
Upvotes: 0
Reputation: 2810
Here for some languages:
C/C++
int i = 65;
char c = i;
printf("%c", c); // prints A
JS
var c = String.fromCharCode(66);
console.log(c); // prints B
C#/Java
char c = (char)67;
// For Java use System.out.println(c)
Console.WriteLine(c) // prints C
Python
c = chr(68) # for Python 2 use c = str(unichr(68))
print(c) # Prints D
Upvotes: 1