Answers for "string reverse in java function"

2

java reverse a string

// Library approach
public static String solution(String str) {
	// StringBuilder is not thread-safe, use StringBuffer
	return new StringBuffer(str).reverse().toString();
}

// DIY approach
public static String solution(String str) {
	char[] chars = str.toCharArray();
	for(int i = 0, j = str.length() - 1; i < j; i++, j--) {
		char ch = chars[i];
		chars[i] = chars[j];
		chars[j] = ch;
	}
	return new String(chars);
}
Posted by: Guest on March-02-2021
2

java string reverse

String str = "Reverse this strings";
//for loop
for (int i = str.length() - 1; i >= 0; i--) {
	System.out.print(str.charAt(i));
}

// StringBuffer for multi thread
StringBuffer sb = new StringBuffer(); 
sb.append(str);
System.out.print(sb.reverse().toString());

// StringBuffer for single thread
StringBuilder sb = new StringBuilder(); 
sb.append(str);
System.out.print(sb.reverse().toString());
Posted by: Guest on June-01-2020
1

Reverse a string in java

// reverse a string using character array
class ReverseUsingCharacterArray
{
   public static void main(String[] args)
   {
      String str = "HelloWorldJava";
      char[] ch = str.toCharArray();
      for(int a = ch.length - 1; a >= 0; a--)
         System.out.print(ch[a]);
   }
}
Posted by: Guest on December-07-2020

Code answers related to "string reverse in java function"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language