将字符(数字)转换为整数的“java”方式是什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3950085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 07:27:42  来源:igfitidea点击:

What's the "java" way of converting chars (digits) to ints

javaintegerchar

提问by Andrei Ciobanu

Given the following code:

鉴于以下代码:

    char x = '5';
    int a0 = x - '0'; // 0
    int a1 = Integer.parseInt(x + ""); // 1
    int a2 = Integer.parseInt(Character.toString(x)); // 2
    int a3 = Character.digit(x, 10); // 3
    int a4 = Character.getNumericValue(x); // 4
    System.out.printf("%d %d %d %d %d", a0, a1, a2, a3, a4);

(version 4 credited to: casablanca)

(第 4 版归功于:卡萨布兰卡

What do you consider to be the "best-way" to convert a char into an int ? ("best-way" ~= idiomatic way)

您认为将 char 转换为 int的“最佳方式”是什么?(“最佳方式”~=惯用方式

We are not converting the actual numerical value of the char, but the value of the representation.

我们不是转换字符的实际数值,而是转换表示的值。

Eg.:

例如。:

convert('1') -> 1
convert('2') -> 2
....

采纳答案by casablanca

回答by Oliver Charlesworth

The first method. It's the most lightweight and direct, and maps to what you might do in other (lower-level) languages. Of course, its error handling leaves something to be desired.

第一种方法。它是最轻量级和最直接的,并且映射到您可能在其他(低级)语言中执行的操作。当然,它的错误处理还有一些不足之处。

回答by jacobm

I'd strongly prefer Character.digit.

我非常喜欢Character.digit.

回答by Peter Lawrey

If speed is critical (rather than validation you can combine the result) e.g.

如果速度很重要(而不是验证,您可以组合结果)例如

char d0 = '0';
char d1 = '4';
char d2 = '2';
int value = d0 * 100 + d1 * 10 + d2 - '0' * 111;

回答by ben

Convert to Ascii then subtract 48.

转换为 Ascii,然后减去 48。

(int) '7' would be 55 
((int) '7') - 48 = 7 
((int) '9') - 48 = 9 

回答by Kevin Ng

The best way to convert a character of a valid digit to an int value is below. If c is larger than 9 then c was not a digit. Nothing that I know of is faster than this. Any digits in ASCII code 0-9(48-57) ^ to '0'(48) will always yield 0-9. From 0 to 65535 only 48 to 57 yield 0 to 9 in their respective order.

将有效数字的字符转换为 int 值的最佳方法如下。如果 c 大于 9,则 c 不是数字。我所知道的没有比这更快的了。ASCII 代码 0-9(48-57) ^ 到 '0'(48) 中的任何数字将始终产生 0-9。从 0 到 65535 只有 48 到 57 按各自的顺序产生 0 到 9。

int charValue = (charC ^ '0');