user2742695
user2742695

Reputation:

Java String change order of words

I have a one string :

String s = "1 = Nick , 2 = Jack , 3 = Sarah , 4 = Katherina";

I want to change order of words like that :

String s = "Nick = 1 , Jack = 2 , Sarah = 3 , Katherina = 4";

How I change the place number and name ?

Upvotes: 0

Views: 2647

Answers (2)

Sean F
Sean F

Reputation: 2390

I know there is a good answer with regex, i'm just providing an alternative without (complex) regex for comparrison to show why regex is the better/simpler solution for this answer.

String s = "1 = Nick , 2 = Jack , 3 = Sarah , 4 = Katherina";
s = s.replace(" ", "");
StringBuilder out = new StringBuilder();
String[] s2 = s.split(",");
for (int i = 0; i < s2.length; i++) {
    String[] s3 = s2[i].split("=");
    if (i == s2.length - 1) {
        out.append(s3[1]).append(" = ").append(s3[0]);
    } else {
        out.append(s3[1]).append(" = ").append(s3[0]).append(" , ");
    }
}
System.out.print(out);

Upvotes: 1

Melih Altıntaş
Melih Altıntaş

Reputation: 2535

String s = "1 = Nick , 2 = Jack , 3 = Sarah , 4 = Katherina";
s = s.replaceAll("(\\d+) = (\\w+)", "$2 = $1");
System.out.println(s);

replaceAll takes two arguments regex and replacement. In first argument we want to pass regex that will match

  • one or more digits - \\d represents one digit,
    \\d+ represents one or more digits
    we can also place it in group by surrounding it with parenthesis (\\d+) - this will be 1st group
  • next should be space, equation mark and another space
  • next, one or more characters - \\w represents any character in range a-z A-Z 0-9 or _
    \\w+ will represent one or more characters of \\w class
    we will also place it in group (\\w+) - this will be 2nd group

Now in replacement part we can use groups with $x where x is group number.
So if we write it as "$2 = $1" it will mean that we want to use matched part stored in group 2 (name) then append " = " and then append matched part stored in group 1 (ID).

Upvotes: 13

Related Questions