给定字符串中的单词可以使用while循环进行计数。一个例子如下:String = Sky is blue
Number of words = 3
演示该程序的程序如下。
示例public class Example {
public static void main(String args[]) {
int flag = 0;
int count = 0;
int i = 0;
String str = "The sunset is beautiful";
while (i
if (str.charAt(i) == ' ' || str.charAt(i) == '\n' || str.charAt(i) == '\t') {
flag = 0;
}else if (flag == 0) {
flag = 1;
count++;
}
i++;
}
System.out.println("The string is: " + str);
System.out.println("No of words in the above string are: " + count);
}
}
上面程序的输出如下。
输出结果The string is : The sunset is beautiful
No of words in the above string are : 4
现在让我们了解上面的程序。
首先,定义字符串str。然后使用while循环获取字符串中的单词数。这是使用初始初始化为0的flag变量完成的。演示此操作的代码段如下所示。int flag = 0;
int count = 0;
int i = 0;
String str = "The sunset is beautiful";
while (i
if (str.charAt(i) == ' ' || str.charAt(i) == '\n' || str.charAt(i) == '\t') {
flag = 0;
}else if (flag == 0) {
flag = 1;
count++;
}
i++;
}
最后,显示字符串和其中的单词数。演示此过程的代码段如下所示。System.out.println("The string is: " + str);
System.out.println("No of words in the above string are: " + count);