Java: parse int value from a char
Asked Answered
D

10

251

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)

Dagoba answered 11/2, 2011 at 11:11 Comment(0)
M
476

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.

Motherland answered 11/2, 2011 at 11:13 Comment(1)
Java 8 added a method Character.digit(char ch, int radix).If you want to constrain yourself to digits 0-9 you could write int x = Character.digit(element.charAt(2), 10);Moujik
C
72

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.

Calabrese answered 29/1, 2014 at 20:28 Comment(4)
What is the reason about that? the result is the substraction between the '0' in the ASCI and the char in the asci???Tarryn
@msj Because the values of '0', '1', '2', ... in ascii are ascending. So e.g. '0' in ascii is 48, '1' is 49, etc. So if you take '2' - '0' you really just get 50 - 48 = 2. Have a look at an ASCII table in order to understand this principle better. Also, 'x' means get the ascii value of the character in Java.Eugenaeugene
@KevinVanRyckegem thank you! I was looking for why - '0' worked...I thought it was some deep magic in how Java interpreted chars or whatever...this truly was a case of me over complicating something...Marenmarena
Although this is a neat trick, it is less readable than using Character.getNumericValueDigiovanni
H
41

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...

Hord answered 11/2, 2011 at 11:17 Comment(5)
Try that with the string "el५" where is the digit 5 in India. :)Motherland
I'm sure you worked hard to find this example... :-) Ok, if you have to parse non-arab digits, avoid this method. Like I said, it's rough. But it's still the fastest method in the 99.999% of cases where it works.Hord
@AlexisDufrenoy, why should subtracting character '0' return the integer value ?Habitancy
Look at the values from the ASCII table char '9' = int 57, char '0' = int 48, this results in '9' - '0' = 57 - 48 = 9Dropper
works like a charm. lol @ counterexample and all the indians who copied your answer. the irony.Jupiter
S
16

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';
Sardius answered 24/8, 2015 at 21:29 Comment(0)
P
6
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);
Pileous answered 21/4, 2015 at 20:25 Comment(0)
N
1

tl;dr

Integer.parseInt( Character.toString( "el5".codePoints().toArray()[ 2 ] ) )

Or, reformatted:

Integer
.parseInt(               // Parses a `String` object whose content is characters that represent digits.
    Character
    .toString(           // Converts a code point integer number into a string containing a single character, the character assigned to that number. 
        "el5"            // A `String` object.
        .codePoints()    // Returns an `IntStream`, a stream of each characters code point number assigned by the Unicode Consortium.
        .toArray()       // Converts the stream of `int` values to an array, `int[]`. 
        [ 2 ]            // Returns an `int`, a code point number. For digit `5` the value here would be 53. 
    )                    // Returns a `String`, "5". 
)                        // Returns an `int`, `5`. 

See this code run live at IdeOne.com.

5

char is legacy

Avoid using char. This type was legacy as of Java 2, essentially broken. As a 16-bit value, the char/Character type cannot represent most characters.

So, avoid calling element.charAt(2). And avoid the single-quote literal such as '5'.

Code point

Instead, use code point integer numbers.

Every one of the over 140,000 characters defined in Unicode is assigned permanently an identifying number. Those numbers range from zero to just over a million.

You can get a stream of all the code point numbers, an IntStream.

String element = "el5😷"; 
IntStream stream = element.codePoints() ;

You can turn that into an array.

int[] codePoints = element.codePoints().toArray() ;

Then access that array.

String out3 = "Third character: " + Character.toString( codePoints[2] ) + " | Code point: " + codePoints[2] + " | Named: " + Character.getName( codePoints[2] ) ;
String out4 = "Fourth character: " + Character.toString( codePoints[3] ) + " | Code point: " + codePoints[3] + " | Named: " + Character.getName( codePoints[3] ) ;

System.out.println( out3 ) ;
System.out.println( out4 ) ;

See this code run live at IdeOne.com.

Third character: 5 | Code point: 53 | Named: DIGIT FIVE

Fourth character: 😷 | Code point: 128567 | Named: FACE WITH MEDICAL MASK

You can test to see if the code point represents a character that is a digit.

if( Character.isDigit( codePoints[2] ) )
{
    String digit = Character.toString( codePoints[2] ) ;
    int i = Integer.parseInt( digit ) ;  // Parse the character `5` as a `int` integer number. 
}
Nerves answered 12/10, 2021 at 1:11 Comment(0)
H
0

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
Hubsher answered 22/1, 2019 at 14:52 Comment(0)
H
0
String element = "el5";
int x = element.charAt(2) - 48;

Subtracting ascii value of '0' = 48 from char

Heaviside answered 11/7, 2019 at 4:58 Comment(0)
K
0

Integer: The Integer or int data type is a 32-bit signed two’s complement integer. Its value-range lies between – 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is – 2,147,483,648 and maximum value is 2,147,483,647. Its default value is 0. The int data type is generally used as a default data type for integral values unless there is no problem with memory.

Example: int a = 10

Character: The char data type is a single 16-bit Unicode character. Its value-range lies between ‘\u0000’ (or 0) to ‘\uffff’ (or 65,535 inclusive).The char data type is used to store characters.

Example: char ch = 'c'

Approaches There are numerous approaches to do the conversion of Char datatype to Integer (int) datatype. A few of them are listed below.

  • Using ASCII Values
  • Using String.valueOf() Method
  • Using Character.getNumericValue() Method

1. Using ASCII values

This method uses TypeCasting to get the ASCII value of the given character. The respective integer is calculated from this ASCII value by subtracting it from the ASCII value of 0. In other words, this method converts the char to int by finding the difference between the ASCII value of this char and the ASCII value of 0.

Example:

// Java program to convert
// char to int using ASCII value
  
class GFG {
    public static void main(String[] args)
    {
  
        // Initializing a character(ch)
        char ch = '3';
        System.out.println("char value: " + ch);
  
        // Converting ch to it's int value
        int a = ch - '0';
        System.out.println("int value: " + a);
    }
}

Output

char value: 3
int value: 3

2. Using String.valueOf() method

The method valueOf() of class String can convert various types of values to a String value. It can convert int, char, long, boolean, float, double, object, and char array to String, which can be converted to an int value by using the Integer.parseInt() method. The below program illustrates the use of the valueOf() method.

Example:

// Java program to convert
// char to int using String.valueOf()
  
class GFG {
    public static void main(String[] args)
    {
        // Initializing a character(ch)
        char ch = '3';
        System.out.println("char value: " + ch);
  
        // Converting the character to it's int value
        int a = Integer.parseInt(String.valueOf(ch));
        System.out.println("int value: " + a);
    }
}

Output

char value: 3
int value: 3

3. Using Character.getNumericValue() method

The getNumericValue() method of class Character is used to get the integer value of any specific character. For example, the character ‘9’ will return an int having a value of 9. The below program illustrates the use of getNumericValue() method.

Example:

// Java program to convert char to int
// using Character.getNumericValue()
  
class GFG {
    public static void main(String[] args)
    {
  
        // Initializing a character(ch)
        char ch = '3';
        System.out.println("char value: " + ch);
  
        // Converting the Character to it's int value
        int a = Character.getNumericValue(ch);
        System.out.println("int value: " + a);
    }
}

Output

char value: 3
int value: 3

ref: https://www.geeksforgeeks.org/java-program-to-convert-char-to-int/

Kapellmeister answered 7/10, 2021 at 23:6 Comment(0)
D
0

The Character.digit method can be used for this. The first argument is the char or int codepoint and the second is the radix.

char c = '5';
int x = Character.digit(c, 10); // result: 5
Discriminatory answered 14/7, 2023 at 3:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.