0

How to extract digits in java.

if there is a 5 digit number how to extract each digit.

18th Dec 2016, 2:53 PM
mamata sethy
mamata sethy - avatar
6 Answers
+ 5
int number = 12345; for(int i = 0; i<5; i++){ System.out.println(number%10); number /= 10; } output: 5 4 3 2 1 demo: https://code.sololearn.com/cMtAc900HAHw
18th Dec 2016, 3:25 PM
Vladimir Honcharenko
Vladimir Honcharenko - avatar
+ 3
@Kirk Schafe, ok. This code will work for number with any count of digits: int number = 12345; String s = "" + number; for(int i = 0; i<s.length(); i++){ int t = Integer.parseInt(s.charAt(i) + ""); System.out.println(t); } output: 1 2 3 4 5 demo: https://code.sololearn.com/cMtAc900HAHw
18th Dec 2016, 3:25 PM
Vladimir Honcharenko
Vladimir Honcharenko - avatar
+ 1
8 ways to convert an integer to a string http://javadevnotes.com/java-integer-to-string-examples#p1 Then I might iterate using subString(). Perhaps someone has a better way.
18th Dec 2016, 3:01 PM
Kirk Schafer
Kirk Schafer - avatar
+ 1
@Vladimir Honcharenko That's interesting. You can even modify it for arbitrary length numbers by breaking when number <10.
18th Dec 2016, 3:10 PM
Kirk Schafer
Kirk Schafer - avatar
+ 1
@V.H. Hey, nice contrast of simple vs. less simple.
18th Dec 2016, 3:22 PM
Kirk Schafer
Kirk Schafer - avatar
0
ya
18th Dec 2016, 3:17 PM
mamata sethy
mamata sethy - avatar