Fabrizio Billeci
Fabrizio Billeci

Reputation: 582

Know the number in a determinate position from a String - Java

I'm getting a number from an addition of Int and then put it as String. I need to know what is the first, second etc. number of the addition. For example the number is 7654, how to know that "7" is the first number? And "6" the second? etc.

          String result += "\nThe result of addition"
          + String.valueOf(add_1) + "+" + String.valueOf(add_2) 
          "+ is" + String.valueOf(int_result);

I want to know the number of a determinate position of the String that contain the result. The string is String.valueOf(int_result), I can use directly int_result too. Thanks!

Upvotes: 0

Views: 105

Answers (2)

EJK
EJK

Reputation: 12524

Just walk each character in the resulting string:

String result = String.valueOf(int_result);
for (int i=0; i< result.length(); i++) {
    char c = result.charAt(i);
    System.out.println("Digit " + i + " = " + c);
    // And if you need this as an integer
    int digit = Integer.parseInt(""+c); 
}

Upvotes: 1

Oyebisi
Oyebisi

Reputation: 724

In Java to get the character at a particular position in a string just use this

String number ="7564";
char c = number.charAt(0);

The above code will asign '5' to char variable c. You can further parse it to integer by doing this

int i = Integer.parseInt(c);

Upvotes: 1

Related Questions