我想知道是否有人有任何想法如何通过一个句子列表返回其中元音最多的单词。
我知道如何计算带有元音的单词并返回计数。只是无法用最元音返回单词..
任何建议都将不胜感激
答案 0 :(得分:3)
String myString = "Java is magical";
// 1. Split your string into an array of words.
String[] words = myString.split(" ");
// 2. Initialise a max vowel count and current max count string variable
int maxVowelCount = 0;
String wordWithMostVowels = "";
// 3. Iterate over your words array.
for (String word : words) {
// 4. Count the number of vowel in the current word
int currentVowelCount = word.split("[aeiou]", -1).length;
// 5. Check if it has the most vowels
if (currentVowelCount > maxVowelCount) {
// 6. Update your max count and current most vowel variables
wordWithMostVowels = word;
maxVowelCount = currentVowelCount;
}
}
// 6. Return the word with most vowels
return wordWithMostVowels;
您可能希望将此功能包含在方法中,并将“myString”值传递给方法。
答案 1 :(得分:2)
这是我认为简单,可读和正确的东西:
public static String findMaxVowels(Collection<String> text) {
String best = null;
int max = 0;
for (String line : text) {
// may need a better definition of "word"
for (String word : line.split("\\s+")) {
int count = countChars(word.toLowerCase(), "aeiou");
if (count > max) {
max = count;
best = word;
}
}
}
return best;
}
public static int countChars(String text, String chars) {
int count = 0;
for (char c : text.toCharArray())
if (chars.indexOf(c) >= 0)
count += 1;
return count;
}
答案 2 :(得分:0)
将单词存储在字符串变量中,并在循环结束后返回字符串。
答案 3 :(得分:0)
你可以将每个句子分成(这个单词是一个提示)为List
个单词,并以最大元音量获得单词。
你每个句子最后会得到一个单词(“最大”),再次处理这个List
个单词(你可以在这里做一个简洁的递归调用)然后你会得到这个单词。文字中元音量最高。
我建议你看一下Collections提供的静态方法,特别是:
public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp)
并最终
public static <T> void sort(List<T> list, Comparator<? super T> c)
您所要做的就是实现一个Comparator,它确定两个单词中元音数量最多的单词。它只是一行两行代码,听起来像是一个功课。
final static Comparator <String> vowelComparator = new Comparator<String>() {
@Override
public final int compare(final String word1, final String word2) {
return vowelCount(word1) - vowelCount(word2);
}
private final int vowelCount(final String word) {
int count = 0;
for (final char c : word.toCharArray()) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
count++;
}
return count;
}
};
public static void main(String...args) {
//Sentences
final List<String> sentences = new ArrayList<String>(3){{
add("This is my first line");
add("Hohoho is my second astonishing line");
add("And finally here is my last line");
}};
//Store the words with highest number of vowels / sentence
final List<String> interestingWords = new LinkedList<>();
for (final String sentence : sentences) {
interestingWords.add(Collections.max(Arrays.asList(sentence.split(" ")), vowelComparator));
}
System.out.println(Collections.max(interestingWords, vowelComparator));
}
答案 4 :(得分:0)
String[] words = yourString.split(" ");
int max = 0;
for(String myStr: words)
max = Math.max(max,myStr.split("[aeiou]").length);
for(String myStr: words)
if(myStr.split("[aeiou]").length == max)
return myStr;