[英]Reverse a String without .reverse method and for loops?
今天我的講師給了我這段代碼,對此我感到有些困惑:
** 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"));**
這是我對代碼的解釋:
它以字符串s
(方法的參數),並着眼於第一個字符。 如果不是c
字符,則將其添加到返回字符串的末尾 ,然后從s
刪除第一個字符。
您剩下的是相同的字符串,但沒有字符c
任何實例。
s = "hello"
return = ""
第一循環:
s = "hello" (set c2 to first char)
c2 = "h" (h is not 'o')
return = "h" (append c2 to end)
第二個循環:
s = "ello"
c2 = "e"
return = "he"
第三循環:
s = "llo"
c2 = "l"
return = "hel"
第四個循環:
s = "lo"
c2 = "l"
return = "hell"
第五圈:
s = "o"
c2 = "o" ("o" matches 'o' character)
return = "hell" (c2 isn't appended)
第六循環:
s = "" (loop ends)
while循環內的行:
if(s.equals("")) return to_return;
表示如果s是一個空字符串,則返回“ return_to”的值,這將結束循環並退出該方法。
由於while()循環永遠不會結束,因此永遠不會到達最后一個return語句。
如果字符串“ s”為null,則方法s.equals(“”)返回null,程序僅在此處終止。
通過c.charAt(0),您將獲得字符串的第一個字符。
如果字符串“ s”的第一個字符不是“ c”,則另一個字符的ASCII值加1。例如-如果字符串“ s”的第一個字符是“ a”,則它將返回'b'作為答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.