例如,您發送一個字符串「喲怎麼了?函數返回4個計數。計算沒有任何循環的字符串中的單詞數量
下面是我寫的:
public class CountString {
public int count(String str){
int count=0;
for(int i=0; i<str.length();i++){
if(str.charAt(i) == ' ')
count++;
}
System.out.printf("\n number of strings: "+ (count+1));
return count+1;
}
}
是否有任何其他方法更快?現在,如何在不包括任何循環的情況下執行相同的工作(for,while,do-while)?
您可以調用其他庫方法來爲您做,但這些方法包含循環。這是不可能的,去了一個沒有循環的前期未知長度的東西。 –