I just want to know if there's a better solution to parse a number from a character in a string (assuming that we know that the character at index n is a number).
String element = "el5";
String s;
s = ""+element.charAt(2);
int x = Integer.parseInt(s);
//result: x = 5
(useless to say that it's just an example)
That's probably the best from the performance point of view, but it's rough:
String element = "el5";
String s;
int x = element.charAt(2)-'0';
It works if you assume your character is a digit, and only in languages always using Unicode, like Java...
Try the following:
str1="2345";
int x=str1.charAt(2)-'0';
//here x=4;
if u subtract by char '0', the ASCII value needs not to be known.
String element = "el5";
int x = element.charAt(2) - 48;
Subtracting ascii value of '0' = 48 from char
Using binary AND
with 0b1111
:
String element = "el5";
char c = element.charAt(2);
System.out.println(c & 0b1111); // => '5' & 0b1111 => 0b0011_0101 & 0b0000_1111 => 5
// '0' & 0b1111 => 0b0011_0000 & 0b0000_1111 => 0
// '1' & 0b1111 => 0b0011_0001 & 0b0000_1111 => 1
// '2' & 0b1111 => 0b0011_0010 & 0b0000_1111 => 2
// '3' & 0b1111 => 0b0011_0011 & 0b0000_1111 => 3
// '4' & 0b1111 => 0b0011_0100 & 0b0000_1111 => 4
// '5' & 0b1111 => 0b0011_0101 & 0b0000_1111 => 5
// '6' & 0b1111 => 0b0011_0110 & 0b0000_1111 => 6
// '7' & 0b1111 => 0b0011_0111 & 0b0000_1111 => 7
// '8' & 0b1111 => 0b0011_1000 & 0b0000_1111 => 8
// '9' & 0b1111 => 0b0011_1001 & 0b0000_1111 => 9
By simply subtracting by char '0'(zero) a char (of digit '0' to '9') can be converted into int(0 to 9), e.g., '5'-'0' gives int 5.
String str = "123";
int a=str.charAt(1)-'0';
String a = "jklmn489pjro635ops";
int sum = 0;
String num = "";
boolean notFirst = false;
for (char c : a.toCharArray()) {
if (Character.isDigit(c)) {
sum = sum + Character.getNumericValue(c);
System.out.print((notFirst? " + " : "") + c);
notFirst = true;
}
}
System.out.println(" = " + sum);
Source: Stackoverflow.com