reverse a string without using string function in java

What you will learn here about java

  • reverse a string without using string function in java

reverse a string without using string function in java

One of the commonly ask java interview program is reverse a string without using string function in java or write a function that reverses a string, without allocating another string or array. You can allocate an additional char variable (character), if needed. The maximum number of iterations (time complexity of the program) should be less than or equal to “n/2”. Here “n” is the length of the string. eg: If string is “Hello” “n” is 5. Number of iterations to reverse the string should be done in <= 5/2 i.e. 2 or 3 iterations.

public class ReverseString 
{

	public static void main(String[] args) 
	{
		System.out.println(reverse("Hello"));
	}
	
	public static String reverse(String str)
	{
		char[] strArray=str.toCharArray();
		for(int i=0;i<strArray.length/2;i++)
		{
			char temp=strArray[i];
			strArray[i]=strArray[strArray.length-i-1];
			strArray[strArray.length-i-1]=temp;
		}
		return String.valueOf(strArray);
	}
	
}

OUTPUT

olleH

You may also like...