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?
StringBuilder Class in Java with Examples
The StringBuilder in Java represents a mutable sequence of characters. Since the String Class in Java creates an immutable sequence of characters, the StringBuilder class provides an alternative to String Class, as it creates a mutable sequence of characters. The function of StringBuilder is very much similar to the StringBuffer class, as both of them provide an alternative to String Class by making a mutable sequence of characters. However, the StringBuilder class differs from the StringBuffer class based on synchronization. The StringBuilder class provides no guarantee of synchronization whereas the StringBuffer class does. Therefore this class is designed for use as a drop-in replacement for StringBuffer in places where the StringBuffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations. Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.
Class Hierarchy:
java.lang.Objectjava.langClass StringBuilder
Syntax:
public final class StringBuilderextends Objectimplements Serializable, CharSequence
Read the Full article 👉️👉️ https://www.geeksforgeeks.org/stringbuilder-class-in-java-with-examples/
Using StringBuilder#reverse we can try:
/* package whatever; // don't place package name! */import java.util.*;import java.lang.*;import java.io.*;/* Name of the class has to be "Main" only if the class is public. */class Ideone{public static void main (String[] args) throws java.lang.Exception { 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 of the regex pattern used in String#replaceAll above, it aims to match every position in the string where there are letters on both sides:
(?<=.) assert that some character precedes(?=.) assert that some character follows
This might help you to reverse words with join ‘-’.
Follow me on Instagram: https://www.instagram.com/ewumesh/
Buy me a coffee: Buyhttps://www.buymeacoffee.com/ewumesh