Java程序对给定字符串中的单词进行计数
给定字符串中的单词可以使用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 < str.length()) {
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 < str.length()) {
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);热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短