-4
String str1 = "1234";
integer j = str1.charAt(1);
print(j);

This returns 50 as a result but I want 2 as an answer.

  • 2
    `charAt` returns a `char` which is a numerical value, representing the ascii value of that character. If you take a look at an ascii table, 50 represents the character `'2'`. You can convert individual digits using `int j= str1.charAt(1)-'0'`. – f1sh Feb 15 '23 at 13:39

1 Answers1

-1
String str1 = "1234";
integer j = str1.charAt(1) - 48 ;
print(j);

// because ASCII value of 0 is 48 and ASCII value of 2 is 50
//so 50 - 48 = 2
  • If you are going to use that trick, then use `'0'` instead of `48`. However, the better approach is to use [`Character.getNumericValue(char)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Character.html#getNumericValue(char)) – Mark Rotteveel Feb 15 '23 at 15:43