Most of the time we came a cross to reverse of a string in interview and interviewer always say it should be optimized.
There are so many ways to reverse a string one of them is mentioned below.
In this way we will reverse the string in half of the iteration of a given string, rather than traversing complete string from start to end.
There are so many ways to reverse a string one of them is mentioned below.
public class StringReverse {
public static void main(String arg[])
{
String string="I AM MIKE MORTAN";
char[] tempCharArray=string.toCharArray();
int start,end=0;
end=tempCharArray.length-1;
for(start=0;start<end;start++,end--)
{
char temp=tempCharArray[start];
tempCharArray[start]=tempCharArray[end];
tempCharArray[end]=temp;
}
System.out.println(new String(tempCharArray));
}
}
In this way we will reverse the string in half of the iteration of a given string, rather than traversing complete string from start to end.
No comments:
Post a Comment