java取字符串中给定词_Java程序对给定字符串中的单词进行计数

本文展示了一个Java程序,用于计算给定字符串中的单词数量。通过使用while循环和标志变量flag,程序能有效地识别并计数字符串中的空格、换行符和制表符之间的单词。示例代码详细解释了如何实现这一功能。
摘要由CSDN通过智能技术生成

给定字符串中的单词可以使用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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值