Maverick
Maverick

Reputation: 2760

how to delimit integers in java?

I have a integer value coming from command line. Its like 12345 or 2343455435 without any delimit characters. How can I get individual pieces of that integer, say like for 12345 I want something like 1, 2, 3, 4 and 5.

Upvotes: 1

Views: 1615

Answers (4)

loloof64
loloof64

Reputation: 5402

you can try something like this :

String numberString = "123456789";
for(byte numberByte:numberString.getBytes()){
    int number = numberByte - '0';
    System.out.println(number);
}

Upvotes: 2

nic
nic

Reputation: 2135

You can use StringTokenizers to get string based on specific tokens or you can just substring the String (use Integer.toString(yourInteger))

int start = 1;
int end = 4;
String substr = "aString".substring(start, end);

Upvotes: 0

anon
anon

Reputation:

Just iterate over all chiffres of the Integer and add a comma if necessary. Something like that:

public static void main(String[] args) {
        int a = 123456;

        String s = Integer.toString(a);
        for (int i = 0; i < s.length() - 1; i++) {
            System.out.print(s.charAt(i) + ",");
        }
        System.out.println(s.charAt(s.length() - 1));
    }

Upvotes: 0

Mike Thomsen
Mike Thomsen

Reputation: 37506

String[] pieces = Integer.toString(myInt).split("[\\d]");
Integer [] numbers = new Integer[pieces.length];
Integer counter = 0;
for (String n : pieces)
    numbers[counter++] = Integer.parseInt(n);

That's assuming it's an integer. Otherwise:

String[] pieces = myNumString.split("[\\d]");

Upvotes: 0

Related Questions