JAVA:统计字符串上的每个单词,并统计单词上的每个字母

标签 java string tokenize

所以,我有一个 java 作业,其中有一个带有短语的字符串。我需要计算该短语包含的每个单词,然后计算每个单词包含的字母数。我已经能够使用 Tokenizer 将短语拆分为单词,然后使用 .countTokens() 计算并打印单词数量。但是,我无法计算每个单词中的字母。

基本上输出应该是这样的:

"Nihil veritas est"
Words: 3
Nihil: 5 letters
Veritas: 7 letters
Est: 3 letters

这是到目前为止我的代码:

public class words {
public static void main(String[] args){
    Scanner in = new Scanner(System.in);
    System.out.println("Please type a phrase.");
    String phrase= in.nextLine();
    StringTokenizer stoken = new StringTokenizer(phrase);
    System.out.println("Your phrase has "+stoken.countTokens()+"words");


}

最佳答案

试试这个:

public class words {
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.println("Please type a phrase.");
        String phrase= in.nextLine();

        String[] words = phrase.split(" ");

        System.out.println("The number of words is:"+words.length);

        for(int i=0; i<words.length; i++){
            System.out.println(words[i]+" is "+words[i].length()+" letters long.");

        }
    }
}

此代码使用 split() 而不是 Tokenizer。对我来说这似乎更容易。

关于JAVA:统计字符串上的每个单词,并统计单词上的每个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22360245/

相关文章:

java - 将列表中的值输入 sparql 查询

java - 使用 Hibernate Criteria 连接不同列上的三个实体所需的帮助

java - 在Java中如何根据单词的长度来定义猜测的次数?

python - Pandas 如何找到单元格的位置以字符串开头

compiler-construction - 分词器应该返回语言关键字吗?

java - 整理文件类

java - Android 在 Canvas 上获取 Bitmap Rect (left, top, right, bottom)

java - 如何在java中向日期变量添加分钟

Python:提取字符串的一部分以某种方式被推到新行

groovy - 在 tokenize() groovy 中包含空值或空格