I have to reverse the given string and parse it with "-". for eg. INPUT: abcde OUTPUT : e-d-c-b-a Any simple solutions?
CodePudding user response:
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
See this code run live at IdeOne.com.
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
CodePudding user response:
Iterate the String
in reverse. Join the output with -
. Like,
String s = "abcde";
System.out.println(IntStream.range(0, s.length())
.mapToObj(i -> String.valueOf(s.charAt(s.length() - i - 1)))
.collect(Collectors.joining("-")));
CodePudding user response:
String letters = "abcde";
(int i = letters.length()-1; i >= 0; i--){
char c = letters.charAt(i);
System.out.print(c "-");
}