Solution: There are many ways to do it, some of them are:
Using for loop
- Declare empty String
reverse. This will contain our final reversed string. - Iterate over an array using for loop from
lastindex to0thindex - Add character to String
reversewhile iterating.
package org.cloud.techtwitter.blogspot;public class ReverseStringForMain {public static void main(String[] args) {String blogName = "techTwitter";String reverse = "";for (int i = blogName.length() - 1; i >= 0; i--) {reverse = reverse + blogName.charAt(i);}System.out.println("Reverse of cloud.techtwitter is: " + reverse);}}
Using recursion
We can also use recursion to reverse a String in java
package org.cloud.techtwitter.blogspot;public class ReverseStringRecursive {public static void main(String[] args) {ReverseStringRecursive rsr = new ReverseStringRecursive();String blogName = "techTwitter";String reverse = rsr.recursiveReverse(blogName);System.out.println("Reverse of cloud.techtwitter is:" + reverse);}public String recursiveReverse(String orig) {if (orig.length() == 1)return orig;elsereturn orig.charAt(orig.length() - 1) +recursiveReverse(orig.substring(0, orig.length() - 1));}}
Char Array (Best without built-ins)
package org.cloud.techtwitter.blogspot;public class ReverseStringOptimal { public static void main(String[] args) { String s = "techTwitter"; char[] arr = s.toCharArray(); int left = 0, right = arr.length - 1; while (left < right) { char temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; left++; right--; } System.out.println(new String(arr)); } }
built-ins
String reversed = new StringBuilder("techTwitter").reverse().toString();
BEST Python Solution (No built-in reverse)
class ReverseString:def reverse(self, s: str) -> str:chars = list(s) # convert string to list (mutable)left, right = 0, len(chars) - 1while left < right:chars[left], chars[right] = chars[right], chars[left]left += 1right -= 1return "".join(chars)# ----- Caller / Main -----if __name__ == "__main__":rs = ReverseString()input_str = "techTwitter"result = rs.reverse(input_str)print("Reversed string:", result)
Don't miss the next article!
Be the first to be notified when a new article or Kubernetes experiment is published.
