简体   繁体   中英

Java using substring() to reverse String

How is the String passed to this method getting reversed? If you pass "ABCD" the string become "DCBA", but I was thinking reverse(str.substring(1)) will call it self until it return "D" which will be concatenated with str.substring(0,1) which is D and the string returned to be "DD".JAVA programming Language.

private static String reverse(String str) {
    if (str.length() <= 1) {
        return str;
    }
    return reverse(str.substring(1)) + str.substring(0, 1);
}

Your best bet with things like this is to work it through on paper and/or step through it statement by statement in the debugger built into your IDE.

  • reverse("ABCD") returns reverse("BCD") + "A" . This is recursion. The call hasn't returned yet, because it needs the result of reverse("BCD") before it can add "A" to it and return.
    • reverse("BCD") returns reverse("CD") + "B" , which waits for reverse("CD") to return
      • reverse("CD") returns reverse("D") + "C" , which waits for reverse("D") to return
        • reverse("D") returns "D"
      • The result of reverse("D") + "C" is "DC" , so now reverse("CD") can return "DC"
    • The result of reverse("CD") + "B" is "DCB" , so now reverse("BCD") can return "DCB"
  • The result of reverse("BCD") + "A" is "DCBA" , so now reverse("ABCD") can return "DCBA"

You can also use the following procedure to solve your problem:

String reversed = new StringBuilder(str).reverse().toString();

Also, according to the requirements about thread safety you can use StringBuffer or StringBuilder

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM