我想知道是否有人对如何通过获取句子列表来返回具有最多元音的单词有任何想法。
我知道如何计算带有元音的单词并返回计数。只是无法返回元音最多的单词..
任何建议将不胜感激
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”值传递给该方法。
以下是我认为简单、易读且正确的内容:
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;
}
您可以将每个句子拆分(这个词是一个提示)成一个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)
您所要做的就是实现一个比较器,它可以在两个单词之间确定哪个单词的元音数量最多。这几乎是两行代码,听起来像是一项家庭作业。
编辑:最后因为他到处都有剧透,所以有那个解决方案。有了记忆,就有一种方法可以让交易者表现得更好,但这不是我想的重点
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));
}
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;
将单词存储在字符串变量中,循环完成后返回字符串。