How do you get the numerical value from a string of digits?

筅森魡賤 提交于 2019-12-25 04:05:24

问题


I need to add certain parts of the numerical string.

for example like.

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.

I tried the charAt(0)+charAt(2) etc, but it returns the digit at those characters instead of adding them. Thanks for your help.


回答1:


I tried the charAt(0)+charAt(2) etc, but it returns the digit at those characters instead of adding them.

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



回答2:


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.

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.




回答3:


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



回答4:


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



回答5:


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


来源:https://stackoverflow.com/questions/28773871/how-do-you-get-the-numerical-value-from-a-string-of-digits

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!