public class WordNumberString {
//带有预定义函数 split
static int numberwords(String string){
int n=0;
字符串[] 字;
//split 将字符串拆分为一组单词
//如果有空格并将它们放在数组中
words = string.split( ”);
返回 words.length;
}
//不带预定义函数 split
static int nombremots_naive(String string){
int n=0;
char c;
//浏览整个字符串
for(int i = 0 ; i < string.length() ; i++){
//字符按字符
c = string.charAt(i);
//避免计算空格
//开头和结尾
//example: 我是程序员”
//如果我们去掉这个测试,即使我们有4个单词,单词数
//也会是6个.
if(i!=0 &&i!=string.length()-1)
if(c==' ')
n++;
}
//如果字符串不为空
//我们添加 1 因为我们
//计算单词之间的空格
//单词,即如果我们有 3 个空格
///那么我们将有 4 个单词
if(n>1)
n++;
返回 n;
}
public static void main(String[] args) {
String string=我是程序员”;
System.out.println(nombremots_naive(字符串));
}
}
Please disable your ad blocker and refresh the window to use this website.