Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JAVA : How can I reverse the string and parse it with '-' in Java

I have to reverse the given string and parse it with "-".
for eg. INPUT: abcde
OUTPUT : e-d-c-b-a
Any simple solutions?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Using StringBuilder#reverse we can try:

String input = "abcde";
StringBuilder sb = new StringBuilder(input);
String output = sb.reverse().toString().replaceAll("(?<=.)(?=.)", "-");
System.out.println(output);  // e-d-c-b-a

For an explanation on the regex pattern used in String#replaceAll above, it aims to match every position in the string where there are letters on both side:

(?<=.)  assert that some character precedes
(?=.)   assert that some character follows
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading