java - 我想在这段代码中放一个字计数器,但不能
问题描述
我需要能够计算我输入的字符串中的单词数。我尝试了很多不同的东西,但没有一个对我有用
import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter some text: ");
String str = in.nextLine().toLowerCase();
String vowels = "aeiou";
System.out.println(str);
int vcount = 0;
int ccount = 0;
for (char c : str.toCharArray()) {
if (Character.isLetter(c)) {
if (vowels.indexOf(c) >= 0)
{
vcount++;
}
else
{
ccount++;
}
}
}
System.out.print("your input has " + vcount + " vowels" + "\n");
System.out.print("your input has " + ccount + " consonants" + "\n");
//System.out.print("your input has " + words + " words");
}
}
解决方案
在空格上拆分字符串,结果数组的长度是您的字数:
int wordcount = str.split( "\\s+" ).length;
"\\s+" 是一个匹配一个或多个空白字符的正则表达式。
推荐阅读
- amazon-cloudfront - HtmlUnit 不加载整个页面
- python - 将字典存储到 Jinja 模板中
- java - 为什么我会收到这个 InvalidPathException
- angular - 如何解决这个问题( /home/user/MagnaFurn/node_modules/@angular/cli/node_modules/@angular-devkit/architect/ )?
- python - 找出一个地理位置是否在两个其他位置之间的线的给定距离内
- python - python pandas - 删除列中的重复项并根据复杂标准保留行
- tsql - TSQL datediff 在一周和几天内返回相同的结果
- solr - 数据导入处理程序可以使用 HikariCP 吗?
- jelastic - jelastic如何挂载/?
- python - 我想要这些数据的校验和提示“1B 02 1D 01 01 0B 03”我想要这些数据是一个 python 软件。输出应该是 B0h