首页 > 解决方案 > 我想在这段代码中放一个字计数器,但不能

问题描述

我需要能够计算我输入的字符串中的单词数。我尝试了很多不同的东西,但没有一个对我有用

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");
   }
}

标签: java

解决方案


在空格上拆分字符串,结果数组的长度是您的字数:

int wordcount = str.split( "\\s+" ).length;

"\\s+" 是一个匹配一个或多个空白字符的正则表达式。


推荐阅读