Tuesday 6 August 2013

Reversing String in java

Hi

Continuing with by earlier post on Webyog interview questions. In this post Ill give the code for one of the question asked in Webyog recruitment drive.

If you have read the earlier post on Webyog recruitment drive you should be aware that they asked us to write a code for reversing the string. This question is not unique to webyog but its asked in a lot of recruitment drives.

I have written a class StringRev, it has a method reverseString(String s). This method can be called from any instance of StringRev.




I have also written a main method which instantiates StringRev and calls the reverseString() to demonstrate how its implemented.

I have used Scanner to read string from the console.  If you write your code interactive its guaranteed that you'll be marked higher than your peers.

Here is the code.

package commoninterviewcodes;

import java.util.Scanner;

public class StringRev {
    public String reverseString(String s){
        String revStr = "";
        for(int i=s.length()-1; i >=0;--i){
            revStr += s.charAt(i);
        }
        return revStr;
    }

    public static void main(String[] args) {
        String s ;

        System.out.println("Type something in.");

        Scanner sc = new Scanner(System.in);
        s = sc.next();

        StringRev strRev = new StringRev();
        System.out.println(strRev.reverseString(s));
    }

}
If you don't understand any part of this code feel free to ask.

Peace.




No comments:

Post a Comment