Reverse a String in JAVA

Screen Shot 2017-05-21 at 1.25.55 PM

  1. Create a function reverseString which takes a String as a parameter and prints out the string in reverse order
  2. Initialize a variable named reverse to hold the reversed String inside the reverseString1 method
  3. Create a for loop starting from the last index of the string passed to the method to 0. Last index is (length of the string – 1) as the index always starts with 0. In the example above it will be 20 (21 – 1)
  4. Decrement by 1
  5. Inside the loop we extract a single character depending on the x variable from the string and concatenate (using + operator) it to the reverse variable till we reach the index 0
  6. Print the reverse variable outside the loop using the
    
    System.out.println();
    
  7. Call the reverseString1 method from the main method as following:
    
    reverseString("This is a test String");
    
  8. Run the program
  9. Input: This is a test String
    Output: gnirtS tset a si sihT
Advertisements

2 thoughts on “Reverse a String in JAVA

Add yours

  1. Hey I rewrote it for you with a couple of pointers you can improve on

    public class StringReverser {
    public static void main(String[] args) {
    String reversed = reverseString(“This is a test String”);
    System.out.println(reversed);
    }

    private static String reverseString(String string) {
    String reverse = “”;
    for(int x = string.length() – 1; x >= 0; x–)
    reverse += string.charAt(x);
    return reverse;
    }
    }

    Class names should begin with a capital to start with.
    Really picky but technically your method didn’t do what it said (It printed out a reversed String).
    Spaces seemed irregular; sometimes you used them, other times you didn’t.
    Also note the use of +=

    Hopefully this helped 🙂

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

Up ↑

%d bloggers like this: