0
import java.util.Scanner;

public class ReverseString {

    public static String reverseString(String str)
    {
        String str2 = "";
        char[] ch = str.toCharArray();
        int length = ch.length;

        for(int i = length-1; i >= 0 ; i--)
            {
            str2 = str2 + ch[i];
            }

        return str2;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        String str = in.nextLine();
        System.out.println(reverseString(str));

    }
}

I want to know that what should I keep in mind while solving this kind of logical problems & making similar programs?

Stultuske
  • 9,296
  • 1
  • 25
  • 37
  • I think these are often matters of taste. If you use str.charAt(i), there is no need for converting to charArray. Some people would rather use str.substring(i, I + 1) – Jeremy Kahan Jan 03 '20 at 13:21
  • 2
    Does this answer your question? [Reverse a string in Java](https://stackoverflow.com/questions/7569335/reverse-a-string-in-java) – mahieus Jan 03 '20 at 13:24
  • 1
    Post this on codereview.stackexchange.com instead. You'll get a better answer. stackoverflow.com is generally for problems, rather than code reviews. – David Lavender Jan 03 '20 at 13:26

3 Answers3

0

To reverse a String you do not want really write a such a logic, you can simply assign your string to a StringBuilder class and call reverse method .

In general when you have such tasks look at API which we can use to ease our task instead of writing such logic.

public static void main(String[] args) {
            Scanner in = new Scanner(System.in);

            String str = in.nextLine();
            StringBuilder sb=new StringBuilder(str);  
            sb.reverse();  
            System.out.println(sb.toString());

        }

simply this will work in your case

Seshidhar G
  • 265
  • 1
  • 9
0

First of all, don't use String concatenation with + sign inside a loop, use StringBuilder for that.

For simple problems like this one, you should try to solving it in few ways, try writing recursive function for example. Also familiarize yourself with memoization and dynamic programming.

Mershel
  • 542
  • 1
  • 9
  • 17
0

here's a recursive example:

private string ReverseString(string inputStr)
{
    if (inputStr.IsNullOrEmpty(inputStr) || inputStr.Length == 1)
        return inputStr;
    else
        return inputStr[inputStr.Length - 1] + Reverse(inputStr.Substring(0, str.Length - 1));
}
Gauravsa
  • 6,330
  • 2
  • 21
  • 30