Friday, December 5, 2014

Reversing a String without recursion.

In this post we will learn how to reverse a string(without recursion). If you are a fresher and preparing for an interview, This can be very helpful for you.

The main idea behind the process is to bring the last character first. As we know in java Strings are not arrays of characters, So you can not access individual characters by array access operator [ ], But don't worry java has given us a method to access every character of string by index.

we will get our last character first, but how we are going to that,
We will use charAt method of String class that given us the character at specified position.
In java String index starts with 0 and ends with length of that string -1.

suppose if have a string  named "hello", Then length would be 5 but index would be from 0 to 4 or we can say 0 to length of hello -1

so we have to start with bring the character at length-1 position first , then length -2 to the second position and so on.


public class StringReverse {

public static void main(String[] args) {

String sampleString = "This is string reversal program";
StringBuilder output = new StringBuilder();

for (int i = sampleString.length() - 1; i >= 0; i--) {

output.append(sampleString.charAt(i));

}

System.out.println(output);

}

}

we are using here Stringbuilder to append every character we get at that position, We also could do it by using String. We have to convert every character into string and using concatenation operator .
That would not be efficient, So we used this.

Feel free to ask any question.


Happy Coding!











No comments:

Post a Comment