Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting up a string

Tags:

java

split

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

like image 434
Mike Avatar asked Apr 22 '26 10:04

Mike


1 Answers

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

String numbers = "12345";
numbers = numbers.replaceAll("(\\d)", "$1 ").trim();
like image 172
vaugham Avatar answered Apr 24 '26 00:04

vaugham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!