你如何从一串数字中得到数值?

时间:2015-02-27 20:41:14

标签: java arrays string numbers switch-statement

我需要添加数字字符串的某些部分。

例如喜欢。

036000291453

我想在奇数位置添加数字,就像

一样

0 + 6 + 0 + 2 + 1 + 5并且等于14。

我尝试了charAt(0)+ charAt(2)等,但它返回这些字符的数字而不是添加它们。谢谢你的帮助。

5 个答案:

答案 0 :(得分:2)

使用charAt获取char(ASCII)值,然后使用int将其转换为相应的charAt(i) - '0'值。 '0'将变为0'1'将变为1等。

请注意,这也会转换非数字字符而不会给您带来任何错误,因此Character.getNumericValue(charAt(i))应该是更安全的选择。

答案 1 :(得分:1)

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

答案 2 :(得分:1)

您可以使用字符。数字()方法

public static void main(String[] args) {
    String s = "036000291453";
    int value = Character.digit(s.charAt(1), 10); 
    System.out.println(value);
}

答案 3 :(得分:1)

下面的代码循环遍历任何一个String的数字,并在末尾打印出奇数的总和

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

答案 4 :(得分:0)

  

我尝试了charAt(0)+ charAt(2)等,但它返回那些数字   字符而不是添加它们。

Character.getNumericValue(string.charAt(0));