简体   繁体   中英

Reverse a String without .reverse method and for loops?

I was handed this code by my lecturer today and I'm SLIGHTLY confused by it:

** String removeAll(char c, String s) {

    String to_return = "";

    while(true) {
        if (s.equals(""))
            return to_return;

        // at this point s is not ""
        char c2 = s.charAt(0);
        if (c2 != c)
        {
            to_return += c2;
        }

        s = s.substring(1);
    }

    return to_return; // won't be reached
}

print(removeAll('o',"hello"));**

Here is my interpration of the code:

  1. if s.equals nothing then return to_return < EXTREMELY DONT GET.
  2. c2 = is equal to the first char of the string s
  3. if c2 does not equal c then to_return += c2< dont fully understand

It takes the String s (the method's parameter) and looks at the first character. If it's not the c character, then add it to the end of the return string, then remove the first character from s .

What you're left with is the same string but without any instances of the character c .

s = "hello"
return = ""

first loop:

s = "hello" (set c2 to first char)
c2 = "h" (h is not 'o')
return = "h" (append c2 to end)

second loop:

s = "ello"
c2 = "e"
return = "he"

third loop:

s = "llo"
c2 = "l"
return = "hel"

fourth loop:

s = "lo"
c2 = "l"
return = "hell"

fifth loop:

s = "o"
c2 = "o" ("o" matches 'o' character)
return = "hell" (c2 isn't appended)

sixth loop:

s = "" (loop ends)

The line inside the while loop:

if(s.equals("")) return to_return;

means if s is an empty string, then return the value of "return_to", which ends the loop and exits the method.

Since the while() loop will never end, the last return statement will never be reached.

  1. If the string 's' is null, then the method s.equals("") returns null and the program terminates here only.

  2. By c.charAt(0), you are getting the first character of the string.

  3. If the first character of the string 's' is not 'c', then the ASCII value of the other character is incremented by 1. For eg- if the first character of string 's' is 'a', then it will return 'b' as the answer.

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