java 如何在不使用库函数的情况下将字符串转换为数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12565237/
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
how to convert string to number without using library function
提问by Basit
Suppose i want to create a method that takes a number as a string and return its number form. Like
假设我想创建一个将数字作为字符串并返回其数字形式的方法。喜欢
getNumber("123456");
public int getNumber(String number) {
//No library function should used. Means i can't do Integer.parseInteger(number).
} //end of getNumber()
How can i implement that method like
我该如何实现该方法,例如
public int getNumber(String number) {
for (int i=0; i<number.length; i++) {
char c = number.getCharacter(i);
///How can i proceed further
} //end of for()
} //end of getNumber()
回答by Bohemian
Without using a library function, subtract the character '0'
from each numeric character to give you its int
value, then build up the number by multiplying the current sum by 10 before adding the next digit's ìnt
value.
在不使用库函数的情况下,'0'
从每个数字字符中减去该字符以获得其int
值,然后通过将当前总和乘以 10 来构建数字,然后再添加下一位数字的ìnt
值。
Java 7
爪哇 7
public static int getNumber(String number) {
int result = 0;
for (int i = 0; i < number.length(); i++) {
result = result * 10 + number.charAt(i) - '0';
}
return result;
}
Java 8
爪哇 8
public static int getNumber(String number) {
return number.chars().reduce(0, (a, b) -> 10 * a + b - '0');
}
This works primarily because the characters 0-9
have consecutive ascii values, so subtracting '0'
from any of them gives you the offset from the character '0'
, which is of course the numeric equivalent of the character.
这主要是因为字符0-9
具有连续的 ascii 值,因此'0'
从它们中的任何一个中减去都会为您提供与字符的偏移量'0'
,这当然是字符的数字等价物。
Disclaimer: This code does not handle negative numbers, arithmetic overflow or bad input.
免责声明:此代码不处理负数、算术溢出或错误输入。
You may want to enhance the code to cater for these. Implementing such functionality will be instructive, especially given this is obviously homework.
您可能希望增强代码以满足这些需求。实现这样的功能将是有益的,尤其是考虑到这显然是家庭作业。
Here's some test code:
下面是一些测试代码:
public static void main(String[] args) {
System.out.println(getNumber("12345"));
}
Output:
输出:
12345
回答by AlexR
Use Integer.parseInt(str)
. Classes Long
, Short
, Double
have similar methods too.
使用Integer.parseInt(str)
. 类Long
,Short
,Double
也有类似的方法了。