[英]How to remove duplicated white spaces in a string and count the number of removed spaces in Java?
[英]How does recursive method to count white spaces in a string work?
我試圖全面了解該方法的工作原理,請參見下面的代碼:
public static void main(String[] args) {
System.out.println(countspaces("a number of spaces "));
}
public static int countspaces(String s) {
if (s.length() == 0)
return 0;
else
return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));
}
我已經使用BlueJ調試了該方法。 該行:
return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));
首先檢查索引為零的字符是否為空格,然后再次調用自身(這使其遞歸),以從索引1開始的s的子字符串作為參數,從而有效地將參數從“多個空格”更改為“直到參數的length()達到0為止。我不明白的是為什么它不返回01000000100100000010(最后一個0是用於終止循環的空字符串s)而是4? 我看不到它在代碼中的總和由1返回
(s.charAt(0) == ' ' ? 1 : 0)
並忽略0。 請告訴我我的推理中缺少的內容。
非常感謝
格熱哥茲(格雷格)
(s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1))
這個基本上將0
s和1
s相加。
注意該方法的返回值int
。 返回值4
非常好。
換句話說:
0 + 1 + 0 + 0 + 0 + 0 + 0 + 1 + 1 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 = 4
由於該方法返回的是int而不是字符串,因此它會添加數字,而不是串聯為字符/字符串。 即
0+1+0+0+0+0+0+0+1+0+0+1+0+0+0+0+0+0+1+0 == 4
不
"0"+"1"+"0"+"0"+"0"+"0"+"0"+"0"+"1"+"0"+"0"+"1"+"0"+"0"+"0"+"0"+"0"+"0"+"1"+"0"
== "01000000100100000010"
下面返回一個int,因為countspaces返回一個int
return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));
為了幫助您理解它,請嘗試用“英語”編寫該函數:
int countspaces( string ) {
if string has no characters {
return 0
}
else {
if first character in string is a space
add 1
otherwise
add 0
to result of countspaces( string_with_first_character_removed )
}
}
遞歸的點是該函數被一遍又一遍地調用,您可以粗略地說這是某種循環。
if (s.length() == 0)
return 0;
這段代碼是遞歸函數的停止條件(因為遞歸此時已停止),當提供的字符串的長度為0時,它將返回0。這里沒有什么要解釋的,我認為這很明顯。
這部分是遞歸函數的核心部分:
return (s.charAt(0) == ' ' ? 1 : 0) + countspaces(s.substring(1));
s.charAt(0) == ' ' ? 1 : 0
s.charAt(0) == ' ' ? 1 : 0
使用三元運算符 ,它檢查字符串中的第一個字符是否為空格,如果為true,則使用值1,否則使用0。
countspaces(s.substring(1))
再次調用該函數,並且子字符串會刪除第一個字符。
函數返回的int
值為0或1,它對返回的值進行求和,如您所知, x + 0 = x
,所以只有第一個字符為空格(函數返回1)的情況才會影響最終結果。
調用將一直進行到函數傳遞自身的空字符串(達到停止條件)時 ,才返回調用堆棧,返回的值與三元運算符的值相加,最后返回預期的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.