Mike
Mike

Reputation: 2313

Splitting up a string

I would like to take the code below and take the 5 number string the I input into the box and output 5 spaces in between each number. So I could enter 12345, and the output would be 1 2 3 4 5.

I'm not sure how to do this, or where to insert the code.

String number;

while (true)
{
number = JOptionPane.showInputDialog("Enter Number");       

if(number.length() >5 )
{
JOptionPane.showMessageDialog(null,"Please enter a 5 digit number!","Try again",
        JOptionPane.PLAIN_MESSAGE);
    }
else break;
}
JOptionPane.showMessageDialog(null,"The new result is " + number,"Results",
        JOptionPane.PLAIN_MESSAGE);

        System.exit(0);

Thanks

Upvotes: 2

Views: 453

Answers (3)

Christoph Leiter
Christoph Leiter

Reputation: 9345

System.out.println("12345".replaceAll("(.(?!$))", "$1 "));

This appends a space to any character that isn't at the end of the string (which means you don't need to call .trim()). If you want more spaces add them at the "$1 " part.

Upvotes: 0

Bala R
Bala R

Reputation: 108937

If for some reason you want a non-regex solution

    String result = "";
    for(char c : number.toCharArray())
    {
        result = result + c + " ";
    }
    result = result.trim();

Upvotes: 0

vaugham
vaugham

Reputation: 1851

regexes are so fun, this code just adds a space after each number :

String numbers = "12345";
numbers = numbers.replaceAll("(\\d)", "$1 ").trim();

Upvotes: 9

Related Questions