java - 如何在字符串中找到元音字母,并在屏幕上打印出元音字母最多的单词?

标签 java string for-loop

我需要找到用户输入的字符串中的所有元音字母,然后在屏幕上打印元音字母最多的单词。
该程序使用用户输入。
用户输入一串小写的单词。
例如

"I like java programming"

它应该读出:

programming

我尝试将字符串拆分成不同的词,这很有效。
我只是不知道如何应用“for”循环来搜索不同的词。 我需要在方法中工作,所以这是我用来在字符串中查找元音的方法:

public void findvowel(){
    for(int index = 0;index < word.length();index++){
    char vowel = word.charAt(index);
    if( (vowel == 'a')||
        (vowel == 'e')||
        (vowel == 'i')||
        (vowel == 'o')||
        (vowel == 'u')){
            System.out.println(vowel);
            }
        }
    }

但我知道这行不通。 你们能帮帮我吗?

最佳答案

public class MaxVowels {
    public static void main(String[] args) {
        String sentence = "This is a loooooooooong sentence";
        int maxVowelCount = 0;
        String wordsWithMostVowels = null;
        String[] words = sentence.split(" ");

        for(String word : words){
            int vowelCount = 0;
            word = word.toLowerCase();
            for(int i = 0; i < word.length() ; i++){
                char x = word.charAt(i);
                if(x == 'a' || x == 'e' || x == 'i' ||
                   x == 'o' || x == 'u'){
                    vowelCount++;
                }
            }
            if(vowelCount > maxVowelCount){
                maxVowelCount = vowelCount;
                wordsWithMostVowels = word;
            }
        }
        System.out.println("Word with most vowels is: " + wordsWithMostVowels);
    }
}  

代码相当简单,无需解释 =)
该代码忽略了两个单词具有相同数量的元音的情况。在这种情况下,第一个单词将用作元音最多的单词。

关于java - 如何在字符串中找到元音字母,并在屏幕上打印出元音字母最多的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19986654/

相关文章:

java - 为什么要显式抛出 NullPointerException 而不是让它自然发生?

java - Cleartrip 航类 API - "Not authorized to access the service"错误

c - 显示 C 中 2 个 char * 字符串之间的差异

java - 为什么 String 是最终的?

java - Retrofit2:如何在响应正文中获取二进制文件

java - 我不明白如何在线程上使用等待和通知

c - 字符串 - 名字和姓氏按字母顺序排列,大写字母

c - 如何在屏幕上显示搜索到的字符串?

c++ - 以下基于范围的 for 循环内幕后的列表是什么?

java - Windows批处理文件多次运行jar文件