java - 如何计算该字符串中每个单词的大小?

标签 java string

我希望能够输出每个单词的字母大小。到目前为止,我的代码仅输出第一个单词的字母大小。我如何让它输出其余的单词?

import java.util.*;

public final class CountLetters {
  public static void main (String[] args) {

    Scanner sc = new Scanner(System.in);
    String words = sc.next();
    String[] letters = words.split(" ");

    for (String str1 : letters) {
       System.out.println(str1.length() ); 
    }   
  } 
}

最佳答案

只是因为next仅返回第一个单词(或也称为第一个“标记”):

String words = sc.next();

要读取整行,请使用nextLine:

String words = sc.nextLine();

那么你正在做的事情应该会起作用。

您可以做的另一件事是继续使用 next 一路(而不是分割),因为 Scanner 已经默认使用空格搜索标记:

while(sc.hasNext()) {
    System.out.println(sc.next().length());
}

关于java - 如何计算该字符串中每个单词的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22155775/

相关文章:

java - 根据字符串移动 Recyclerview 项目位置

perl - 如何在 Perl 中用递增的数字替换 token ?

javascript - 想要在 javascript 中编写正则表达式,它将检查所有提到的字符是否至少存在

c++ stol 抛出字符串长度为 10 或更长的超出范围异常

java - make if 只检查一个命令

c# - 切换字符串的部分

java - 如何将 www.mysite.com/page 映射到 page.mysite.com?

java - AsyncTask 的 publishProgress 方法是异步的吗?

java - Camel 文件序列号

java - 在同一表面上映射多个纹理