繁体   English   中英

如何将字符串中的所有数字移动到字符串的开头?

[英]How to move all digits in a string to the beginning of the string?

对于以下字符串:

String str="asd14sd67fgh007";

我想输出像:

1467007asdsdfgh

我知道如何分割字符串,但我不知道如何得到它。 对于拆分,我有这个代码:

public static void main(String[] args) {
    String str="asd14sd67fgh007";
    Pattern pattern = Pattern.compile("\\w+([0-9]+)\\w+([0-9]+)");
    Matcher matcher = pattern.matcher(str);
    for(int i = 0 ; i < matcher.groupCount(); i++) {
        matcher.find();
        System.out.println(matcher.group());
    }
}

2 replaceAll()可以做到(如果你真的想使用正则表达式:P):

public static void main(String[] args) {
        String s= "asd14sd67fgh007";
        String correctedString = s.replaceAll("\\D+", "") + s.replaceAll("\\d+", "");
        System.out.println(correctedString);
}

O / P:

1467007asdsdfgh

注意 :

"\\\\D+" ==>用""替换所有非数字字符。 (会给你所有数字)。

"\\\\d+" ==>用""替换所有数字(将为您提供所有非数字字符)

这是使用char[]StringBuilder的简单解决方案:

String input = "asd14sd67fgh007";
StringBuilder output = new StringBuilder();
// temporary, for storing alphabetic characters
StringBuilder temp = new StringBuilder();
// iterating input's characters one by one
for (char c: input.toCharArray()) {
    // digits, go to output in their order
    if (Character.isDigit(c)) {
        output.append(c);
    }
    // letters, go to temporary to be appended later
    else if (Character.isAlphabetic(c)){
        temp.append(c);
    }
    // punctuation gets lost
}
// appending temporary alphabetics to digits and printing
System.out.println(output.append(temp));

产量

1467007asdsdfgh

你可以做这样的事情。 在循环遍历所有char使用StringBuilder跟踪正面和背面。

String str="asd14sd67fgh007";
StringBuilder front = new StringBuilder(str.length());
StringBuilder back = new StringBuilder(str.length());
for (char c : str.toCharArray()){
    if (c>=48 && c<=57){ //If numeric
        front.append(c);
    }else{
        back.append(c);
    }
}
front.append(back.toString());
System.out.println(front.toString());

产量

1467007asdsdfgh

如果不必使用正则表达式,则可以使用循环来实现输出:

    String str = "asd14sd67fgh007";
    String digits = "", characters = "";

    for (int i = 0; i < str.length(); ++i) {
        if (Character.isDigit(str.charAt(i))) {
            digits += str.charAt(i);
        } else {
            characters += str.charAt(i);
        }
    }

    System.out.println("Result is :" + digits + characters);

暂无
暂无

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

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