Java how to return a part of a number?

Viewed 130

I'm trying to return a part of a number, like so:

int foo = 123456789;

System.out.println( foo[0-3] ); //123

I'd also like to get a slice of the number for different indexes, from 2 to 5 for example. In Python, it is pretty straightforward but for some reason it's not so easy to do the same in Java.

4 Answers

foo is a number, not an array, so you can't do a slice on it. You need to convert it to String first and do a substring (= char array slice):

int foo = 123456789;
String slice = String.valueOf(num).substring(0, 3);
System.out.println(slice); // prints 123

If you need to use it as a number again, you need to convert it back to int:

int converted = Integer.parseInt(slice);

You could convert the int to String, substring it and parse it to an integer again:

int foo = 123456789;
String foorStr = Integer.toString(foo);
String fooSubstr = foo.substring(0, 3); //the last index is exclusive
int fooParted = Integer.parseInt(fooSubstr);

int v=123456; System.out.println(String.valueOf(v).substring(1,3));

There is already a method parseInt that lends itself to this. It takes a String value, starting location, ending location, and a radix. You can make it a little easier as follows:

System.out.println(getSubNumber(123456789, 2,6));

public static int getSubNumber(int value, int start, int end) {
    return Integer.parseInt(Integer.toString(value), start, end, 10);
}

prints

3456

or forego the method and just use Integer.parseInt directly. There is an equivalent Long.parseLong for long types.

Related