简体   繁体   English

分裂一个字符串

[英]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. 我想取下面的代码并将我输入的5个数字字符串放入框中,并在每个数字之间输出5个空格。 So I could enter 12345 , and the output would be 1 2 3 4 5 . 所以我可以输入12345 ,输出为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 谢谢

regexes are so fun, this code just adds a space after each number : 正则表达式非常有趣,这段代码只是在每个数字后面添加一个空格:

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

If for some reason you want a non-regex solution 如果由于某种原因你想要一个非正则表达式解决方案

    String result = "";
    for(char c : number.toCharArray())
    {
        result = result + c + " ";
    }
    result = result.trim();
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() ). 这会向不在字符串末尾的任何字符添加空格(这意味着您不需要调用.trim() )。 If you want more spaces add them at the "$1 " part. 如果您想要更多空格,请在"$1 "部分添加它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM