-2

I can't get my function to return the reversed string. I keep getting the original string, plus the reversed sting attached together.

P.S this is obviously a question from someone new. Cut me some slack and save me from the horribly demoralizing down vote.

    int i;
    reverse = reverse.replaceAll("[^a-zA-Z]+", "").toLowerCase();

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

    return reverse;
}
JWL1988
  • 1
  • 2

3 Answers3

3

You need another String (or some other method / memory) to build your return value (consider "a", starting from the end of the String add "a" - thus you get "aa"). Instead, I would use a StringBuilder - and the entire method might be written like

return new StringBuilder(reverse.replaceAll("[^a-zA-Z]+", "")
        .toLowerCase()).reverse().toString();
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • Hi Elliot, I tried to look up some of the documentation, but I couldn't really understand why the "+" is there. What would happen if I left that out? – JWL1988 Jul 13 '17 at 23:23
  • @JWL1988 It matches one or more consecutive non-letters, since you replace them all anyway it wouldn't really change anything in this specific case. The '+' *specifically* adds "or more". Consider `"a b"` ("a", 3 spaces and "b"), `"a b".split("\\s+")` yields a very different result to `"a b".split("\\s")` – Elliott Frisch Jul 14 '17 at 02:16
2

Change the snippet to,

String reverse_string="";
for (i = reverse.length() - 1; i >= 0; i--) {
    reverse_string += reverse.charAt(i);
    }
return reverse_string;

You will need a separate String variable to contsruct the newly reversed string.

Joey Pinto
  • 1,735
  • 1
  • 18
  • 34
2

Why not just let the existing Java api do this for you?

 String someString = "somestring123";
    System.out.println(new StringBuilder(someString).reverse().toString());

output: StringBuilder

Perrin
  • 68
  • 1
  • 7