243

我只想知道是否有更好的解决方案来从字符串中的字符解析数字(假设我们知道索引 n 处的字符是数字)。

String element = "el5";
String s;
s = ""+element.charAt(2);
int x = Integer.parseInt(s);

//result: x = 5

(不用说这只是一个例子)

4

9 回答 9

467
于 2011-02-11T11:13:14.077 回答
67

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.

于 2014-01-29T20:28:04.180 回答
39

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

于 2011-02-11T11:17:32.017 回答
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';
于 2015-08-24T21:29:10.703 回答
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);
于 2015-04-21T20:25:04.157 回答
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
于 2019-01-22T14:52:20.303 回答
0
String element = "el5";
int x = element.charAt(2) - 48;

Subtracting ascii value of '0' = 48 from char

于 2019-07-11T04:58:33.550 回答
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/

于 2021-10-07T23:06:19.410 回答
0

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. 
}
于 2021-10-12T01:11:56.463 回答