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).
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 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);
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 Character.getNumericValue(char).
String element = "el5";
int x = Character.getNumericValue(element.charAt(2));
System.out.println("x=" + x);
produces:
x=5
The nice thing about getNumericValue(char)
is that it also works with strings like "el٥"
and "el५"
where ٥
and ५
are the digits 5 in Eastern Arabic and Hindi/Sanskrit respectively.
String element = "el5";
int x = element.charAt(2) - 48;
Subtracting ascii value of '0' = 48 from char
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';