簡體   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