java - 如何计算每个单词的字母

标签 java android string int word

我想知道如何编写一个方法来计算单词的数量和每个单词字母的数量 例如,如果输入是“The Blue Sky”作为返回,我会拿一些东西告诉我有 3 个单词 3 个字母 4 个字母 3 个字母

我已经找到这段代码了

public static int countWords(String s){

    int wordCount = 0;

    boolean word = false;
    int endOfLine = s.length() - 1;

    for (int i = 0; i < s.length(); i++) {
        // if the char is a letter, word = true.
        if (Character.isLetter(s.charAt(i)) && i != endOfLine) {
            word = true;
            // if char isn't a letter and there have been letters before,
            // counter goes up.
        } else if (!Character.isLetter(s.charAt(i)) && word) {
            wordCount++;
            word = false;
            // last word of String; if it doesn't end with a non letter, it
            // wouldn't count without this.
        } else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {
            wordCount++;
        }
    }
    return wordCount;
}

我非常感谢能得到的任何帮助!谢谢!

最佳答案

第 1 步 - 使用空格分隔符计算句子中的单词数。

 String CurrentString = "How Are You";
    String[] separated = CurrentString.split(" ");
    String sResultString="";
    int iWordCount = separated.length;
    sResultString = iWordCount +" words";

第 2 步 - 计算每个单词中的字母数。

    for(int i=0;i<separated.length;i++)
    {
    String s = separated[i];
    sResultString = sResultString + s.length + " letters ";
    }

// Print sResultString 

关于java - 如何计算每个单词的字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27725274/

相关文章:

webview 输入字段中的 Android 电子邮件友好键盘

在某些设备上转到主屏幕时 Android 服务停止

c - 从控制台读取正好 50 个字符(49 +1 表示 null),仅忽略所有初始空格

python - 如何对字符串列表中的元素进行编号并返回一个新列表?

sql - 如何在 SQLite 查询中转义字符串中的双引号?

java - 为 POJO 类生成执行 ANT 脚本时进行 Hibernate 日志记录

java - 通过 java servlet 实现处理邮件协议(protocol)

android:launchMode ="singleInstance"使应用程序非常慢

java - 如何用Java计算CRC8

java - 使用不同数据集的参数化 android 测试