Reversing a String from user's input

I have written code to prompt user to input a sentence which will be displayed reversed by the system. I have managed it with a bit of help, but I now struggle to comment my codes to explain each piece of it. I somewhat understand what I have done, but I feel like I do not master the "whys" of each line.

Anyone able to help with my comments ?

public static void main(String[] args) {
    // TODO Auto-generated method stub

    String original = "", reverse = ""; // Setting the strings values
    Scanner in = new Scanner(System.in); // Scanner is equal to input from user

    while(!original.contains("exit"))
    // As long as user does not input "exit", user will be prompt to enter a sentence
    {
        original = "";
        reverse = "";
        System.out.println("Enter a sentence to be reversed: ");
        original = in.nextLine(); // Setting "original" to be equal to user's input

        int length = original.length(); // Getting user's input character length (original)
        for (int i = length - 1; i >= 0; i--) // Getting input from the last character to be reversed
        reverse = reverse + original.charAt(i); //Setting "reverse" to the input "original" characters

        System.out.println(reverse); // Printing the input reversely
    }

}

Most blurry parts being the:

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

and the:

reverse = reverse + original.charAt(i);

Here's an explanation of what's happening.

public static void main(String[] args) {
    String original = "", reverse = ""; // Create empty variables to hold the input and output
    Scanner in = new Scanner(System.in); // Create an object to read from StdIn

    while(!original.contains("exit"))
    // Read from StdIn as long as user does not input "exit"
    {
        original = "";
        reverse = "";
        System.out.println("Enter a sentence to be reversed: ");
        original = in.nextLine(); // Save the user's input as "original"

        int length = original.length(); // Get the length of the input
        for (int i = length - 1; i >= 0; i--) // Iterate over each character of the input, starting from the end until you reach the beginning and add the character to the "reverse" string
        reverse = reverse + original.charAt(i); 

        System.out.println(reverse); // Output the result
    }
}

Having two separate comments to explain the for loop doesn't make much sense as each of the two lines are meaningless without the other.

Different methods to reverse a string in C/C++, Given a string, write a C/C++ program to reverse it. string-reverse A quickly written program for reversing a string //Use of reverse iterators. string rev� In the recursive method, we swap characters at the beginning and the end of the string and move towards the middle of the string. This method is inefficient due to repeated function calls. C program to reverse a string using pointers. Now we will invert a string using pointers or without using the library function strrev.

How do you reverse a string in Python?, Strings can be reversed using slicing. To reverse a string, we simply create a slice that starts with the length of the string, and ends at index 0. The slice statement means start at string length, end at position 0, move with the step -1 (or one step backward). means to take what is currently stored in the reverse variable and adding a new character at the end + original.charAt (i). This produces a new String which gets assigned back to the reverse variable, overriding what was in it before like @agim mentioned in his answer. Here are some other alternatives you could consider.

Understanding

for (int i = length - 1; i >= 0; i--)
reverse = reverse + original.charAt(i);

Which you should reformat to look like

for (int i = length - 1; i >= 0; i--)
    reverse = reverse + original.charAt(i);

or

for (int i = length - 1; i >= 0; i--) {
    reverse = reverse + original.charAt(i);
}

means to take what is currently stored in the reverse variable and adding a new character at the end + original.charAt(i). This produces a new String which gets assigned back to the reverse variable, overriding what was in it before like @agim mentioned in his answer.

Here are some other alternatives you could consider. Especially with using StringBuilder because it has a reverse() function built into it, if you're wanting to reverse the sentence by character.

import java.util.*;

public class JavaFiddle
{
  public static void main(String[] args)
  {
    String sentence = "The quick brown fox jumps over the lazy dog";

    // Print sentence forward
    System.out.println(sentence);

    // Print sentence backwards by words
    String[] words = sentence.split(" ");
    for (int i = words.length - 1; i >= 0; i--) {
      System.out.print(words[i] + " ");
    }
    System.out.println();

    // Print sentence backwards by character
    for (int i = sentence.length() - 1; i >= 0; i--) {
      System.out.print(sentence.charAt(i));
    }
    System.out.println();

    // Print sentence backwards by character using StringBuilder;
    StringBuilder reverseSentence = new StringBuilder(sentence);
    System.out.println(reverseSentence.reverse());
  }
}

RESULT

The quick brown fox jumps over the lazy dog
dog lazy the over jumps fox brown quick The 
god yzal eht revo spmuj xof nworb kciuq ehT
god yzal eht revo spmuj xof nworb kciuq ehT

How to Reverse A String In Java | Java Reverse Programs, Reverse a String using String Builder / String Buffer Class. StringBuffer and StringBuilder comprise of an inbuilt method reverse() which is used to reverse the characters in the StringBuffer. This method replaces the character sequence in the reverse order. C program to Reverse a String Example 1. This reverse a string in c program allows the user to enter any string or character array. Next, it will use For Loop to iterate each character in that string, and save the characters in reverse order.

Reverse a string in Java, You can use this: new StringBuilder(hi).reverse().toString(). Or, for versions earlier than JDK 1.5, use java.util.StringBuffer instead of StringBuilder — they have� Enter a string: hello olleh In the above program, the built-in methods are used to reverse a string. First, the string is split into individual array elements using the split() method. str.split("") gives ["h", "e", "l", "l", "o"].

Reverse a string in Java, Reverse a string in Java. Java program to reverse a string that a user inputs. The charAt method is used to get� Split the string into an array of its characters, reverse the array and then join it back up again into a string. Got the idea from here. If you just want to reverse the order of the words in the sentence (not the characters themselves) then simply.split () and.join () with a space as follows:

Reverse a String in Java, In the above code, we are basically reading in a String from the user afterwhich we will begin an iteration loop that will build the new reversed� There are many ways of reversing a String in Java for whatever reason you may have. Today, we will look at a few simple ways of reversing a String in Java. For example, the string “Reverse Me” once reversed will be “eM esreveR”. We will start by looking at the most traditional method with the least help from external Java classes.

Comments
  • Use a debugger and step through your code with a small test input.
  • For loop** - Looping over each character of the string starting from last character of the string. reverse** - appending each char to form new string. I would suggest to use StringBuilder instead of using String concatenation.
  • thank you, this is very helpful to break things down that way.
  • thank you, the length - 1 was slightly confusing even though my understanding was not far from the truth. This is very helpful. Thanks !
  • If it was helpful, you might consider to vote up this answer, that's actually the idea behind stack overflow.
  • HI @agim, apologies, didn't mean to be disrespectful, I'm starting to use this platform, as I am beginning Java as well. Not familiar with all this. Thanks again.