Java:从 char 解析 int 值

发布于 2024-10-16 17:17:32 字数 213 浏览 7 评论 0原文

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

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

//result: x = 5

(没什么用,这只是一个例子)

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

爱冒险 2024-10-23 17:17:32

尝试 Character.getNumericValue(字符)

String element = "el5";
int x = Character.getNumericValue(element.charAt(2));
System.out.println("x=" + x);

产生:

x=5

getNumericValue(char) 的好处是它还可以处理 "el٥""el५" 等字符串,其中 ٥ 分别是东阿拉伯语和印地语/梵语中的数字 5。

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.

眼眸印温柔 2024-10-23 17:17:32

尝试以下操作:

str1="2345";
int x=str1.charAt(2)-'0';
//here x=4;

如果 u 减去 char '0',则不需要知道 ASCII 值。

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.

感受沵的脚步 2024-10-23 17:17:32

从性能的角度来看,这可能是最好的,但它很粗糙:

String element = "el5";
String s;
int x = element.charAt(2)-'0';

如果你假设你的字符是一个数字,它就可以工作,并且只有在总是使用 Unicode 的语言中,比如 Java...

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

幽蝶幻影 2024-10-23 17:17:32

通过简单地减去 char '0'(零),可以将 char(数字 '0' 到 '9')转换为 int(0 到 9),例如,'5'-'0' 得到 int 5。

String str = "123";

int a=str.charAt(1)-'0';

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';
oО清风挽发oО 2024-10-23 17:17:32
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);
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);
遗失的美好 2024-10-23 17:17:32

tl;dr

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

或者,重新格式化:

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

请参阅在 IdeOne.com 上实时运行的代码

5

char 是遗留的

避免使用char。这种类型从 Java 2 开始就是遗留的,基本上已经被破坏了。作为 16 位值,char/Character 类型无法表示大多数字符。

因此,请避免调用 element.charAt(2)。并避免使用单引号文字,例如 '5'

代码点

请使用代码点整数。

超过 140,000 个字符中定义的每一个en.wikipedia.org/wiki/Unicode" rel="nofollow noreferrer">Unicode 被永久分配一个识别号码。这些数字范围从零到略多于一百万。

您可以获得所有代码点编号的流,IntStream

String element = "el5

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. 
}
聽兲甴掵 2024-10-23 17:17:32

将二进制 AND0b1111 结合使用:

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

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
余生共白头 2024-10-23 17:17:32
String element = "el5";
int x = element.charAt(2) - 48;

从 char 中减去 '0' = 48 的 ascii 值

String element = "el5";
int x = element.charAt(2) - 48;

Subtracting ascii value of '0' = 48 from char

当梦初醒 2024-10-23 17:17:32

Integer:Integer 或 int 数据类型是 32 位有符号二进制补码整数。其值范围介于 – 2,147,483,648 (-2^31) 到 2,147,483,647 (2^31 -1)(含)之间。其最小值为 – 2,147,483,648,最大值为 2,147,483,647。它的默认值为0。除非内存没有问题,否则int数据类型通常用作整数值的默认数据类型。

Example: int a = 10

字符:char 数据类型是单个 16 位 Unicode 字符。它的值范围在'\u0000'(或0)到'\uffff'(或65,535)之间。char数据类型用于存储字符。

Example: char ch = 'c'

方法
有多种方法可以将 Char 数据类型转换为 Integer (int) 数据类型。下面列出了其中一些。

  • 使用 ASCII 值
  • 使用 String.valueOf() 方法
  • 使用 Character.getNumericValue() 方法

1. 使用 ASCII 值

此方法使用 TypeCasting 来获取给定字符的 ASCII 值。相应的整数是通过从 ASCII 值 0 中减去该 ASCII 值来计算的。换句话说,该方法通过查找该 char 的 ASCII 值与 ASCII 值 0 之间的差值来将 char 转换为 int。

示例:

// 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);
    }
}

输出

char value: 3
int value: 3

2. 使用 String.valueOf() 方法

String 类的 valueOf() 方法可以将各种类型的值转换为 String 值。它可以将 int、char、long、boolean、float、double、object 和 char 数组转换为 String,可以使用 Integer.parseInt() 方法将其转换为 int 值。下面的程序说明了 valueOf() 方法的用法。

示例:

// 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);
    }
}

输出

char value: 3
int value: 3

3. 使用Character.getNumericValue() 方法

Character 类的getNumericValue() 方法用于获取任何特定字符的整数值。例如,字符“9”将返回值为 9 的 int。下面的程序说明了 getNumericValue() 方法的使用。

示例:

// 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);
    }
}

输出

char value: 3
int value: 3

参考:https://www.geeksforgeeks。 org/java-program-to-convert-char-to-int/

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/

泪之魂 2024-10-23 17:17:32

字符.digit 方法可用于此。第一个参数是 char 或 int 代码点,第二个参数是基数。

char c = '5';
int x = Character.digit(c, 10); // result: 5

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文