java 你如何从一串数字中得到数值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28773871/
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 do you get the numerical value from a string of digits?
提问by Winterone
I need to add certain parts of the numerical string.
我需要添加数字字符串的某些部分。
for example like.
例如喜欢。
036000291453
036000291453
I want to add the numbers in the odd numbered position so like
我想在奇数位置添加数字,例如
0+6+0+2+1+5 and have that equal 14.
0+6+0+2+1+5 并且等于 14。
I tried the charAt(0)+charAt(2) etc, but it returns the digit at those characters instead of adding them. Thanks for your help.
我尝试了 charAt(0)+charAt(2) 等,但它返回这些字符的数字而不是添加它们。谢谢你的帮助。
回答by emlai
Use charAt
to get to get the char
(ASCII) value, and then transform it into the corresponding int
value with charAt(i) - '0'
. '0'
will become 0
, '1'
will become 1
, etc.
使用charAt
get 获取char
(ASCII)值,然后用 将其转换为对应的int
值charAt(i) - '0'
。'0'
将成为0
,'1'
将成为1
,等等。
Note that this will also transform characters that are not numbers without giving you any errors, thus Character.getNumericValue(charAt(i))
should be a safer alternative.
请注意,这也将转换不是数字的字符而不会给您任何错误,因此Character.getNumericValue(charAt(i))
应该是一个更安全的选择。
回答by Omar MEBARKI
You can use Character.digit()method
您可以使用字符。数字()方法
public static void main(String[] args) {
String s = "036000291453";
int value = Character.digit(s.charAt(1), 10);
System.out.println(value);
}
回答by Code Whisperer
Below code loops through any number that is a String and prints out the sum of the odd numbers at the end
下面的代码循环遍历字符串中的任何数字,并在末尾打印出奇数的总和
String number = "036000291453";
int sum = 0;
for (int i = 0; i < number.length(); i += 2) {
sum += Character.getNumericValue(number.charAt(i));
}
System.out.println("The sum of odd integers in this number is: " + sum);
回答by Nicholas Hirras
String s = "036000291453";
int total = 0;
for(int i=0; i<s.length(); i+=2) {
total = total + Character.getNumericValue(s.charAt(i));
}
System.out.println(total);
回答by Voldemort
I tried the charAt(0)+charAt(2) etc, but it returns the digit at those characters instead of adding them.
我尝试了 charAt(0)+charAt(2) 等,但它返回这些字符的数字而不是添加它们。
Character.getNumericValue(string.charAt(0));