1

So I'm trying to print a string backward, but it doesn't start where I want it to. Whenever I run the code it says it starts at -1. Here's my code:

public static String reverse(String str)
    {
        //This method will return a string that reverses the letters in 'str'
        //Example:
        //   reverse("abcdef") returns "fedcba"
        String result="";

        for(int i = str.length()-1; i >= 0; i--){
           result = result + str.substring(i-1, i);
        }

        return result;
    }

How would I get it to subtract 1 instead of it thinking it's a negative one?

2
  • 1
    you should use: i > 0 not i >= 0 Commented Nov 11, 2020 at 4:58
  • 2
    Try changing str.substring(i-1, i) to str.substring(i, i+1) Commented Nov 11, 2020 at 4:59

2 Answers 2

2

Well, there is a logic issue in the code.

Correct implementation should be

//using subString the way you are trying
public static String reverse(String str)
    {
       String result="";

        for(int i = str.length()-1; i >= 0; i--){
           result = result + str.substring(i, i+1);
        }

        return result;
    }

Alternative Approaches using charAt

public static String reverse(String str)
    {
        String result="";

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

        return result;
    }

Using String Builder(Probably the best method if you are not writing he code for learning purpose)

String reversed = new StringBuilder(str).reverse().toString();
Sign up to request clarification or add additional context in comments.

Comments

0

Why not splice characters one by one

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.