简体   繁体   中英

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

For the following string:

String str="asd14sd67fgh007";

I want output like:

1467007asdsdfgh

I know how to split a string, but I don't know how to get this. For split, I have this code:

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() can do it (If you really want to use regex :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

Note :

"\\\\D+" ==> replace all non-numeric characters with "" . (will give you all numbers).

"\\\\d+" ==> replace all digits with "" (will give you all non-numeric characters)

Here's a simple solution using char[] s and StringBuilder s:

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));

Output

1467007asdsdfgh

You can do something like this. Use StringBuilder to keep track of the front and back while looping through all the char s.

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());

Output

1467007asdsdfgh

If it is not mandatory to use regular expression, you can just use a loop to achieve the output:

    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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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