Martins Martins -4 years ago 85
Java Question

String character swap

I have problem with character swap in string.
e.g. I have string "sdgk4e5s3gj6ds3h6fggh" and I need code that can swap numbers with character.

The result should look something like this: "sdgke4s5g3jd6sh3f6ggh"
I have got to the point where I make char array out of String, but I don't know what to do next. Any help?

Answer Source

If I understand correctly what you are asking, a simple regex could solve your problem:

String result = "sdgk4e5s3gj6ds3h6fggh".replaceAll("(\\d)(\\D)", "$2$1")

which basically inverts 2 characters every time it finds one digit followed by one non-digit.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download