例如,您发送一个字符串“ Yo What's up dog?”。对于一个函数,该函数返回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)?
您可以这样做:
String s = "Yo what’s up dog?";
String[] arr = s.split(" ");
System.out.println(arr.length); //prints 4
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句