From the String array, you need to output a word in which a certain letter is hidden in the maximum number of times.
For example, given
String [] words ={"black","one","doodle","snack","divine"};

 String let = "d"; 

The program should display the word doodle

My code is:

 public static void main(String[] args) { String let = "d"; String [] words ={"black","one","doodle","snack","divine"}; for (int i = 0; i <words.length; i++) { if (words[i].contains(let)) { System.out.println(words[i]); } } } 

I can print the words in which the letter is found, but how can I output the word with the maximum repetition of the letter?

2 answers 2

Another solution to the forehead:

 char let = 'd'; String[] words = {"black", "one", "doodle", "snack", "divine"}; int max = 0, indexOfMax = -1; for (int i = 0; i < words.length; i++) { int wordLength = words[i].length(); int counter = 0; for (int leti = 0; leti < wordLength; ++leti){ if(words[i].charAt(leti) == let){ ++counter; } } if(counter>max){ max = counter; indexOfMax = i; } } 

and Java 8 solution

 long max = 0; int indexOfMax = -1; for (int i = 0; i < words.length; i++) { long counter = words[i].chars().filter(ch -> ch == let).count(); if(counter>max){ max = counter; indexOfMax = i; } } 

For output use:

 if(max==0){ System.out.println("Not present"); } else { System.out.println(words[indexOfMax]); } 
  • why do we assign the max variable to -1? why not zero, from this something will change? - Oleg Khegay
  • And this is a true remark, by the way, so it will work more correctly xD - Komdosh
  • and indexOfMax = -1; it is also not necessary to assign to -1 as I understand it. Can any value be in principle? - Oleg Khegay
  • Here it is better to -1, if you specify the value that exists in the array, there may be a situation where you will debug why for a long time it gives the wrong value, and will crash with an error - Komdosh

Something like this

  public static void main(String[] args) { String let = "d"; String[] words = { "black", "one", "doodle", "snack", "divine" }; int maxLetter = count(words[0], let); String wordWithMaxLetters = null; for (int i = 1; i < words.length; i++) { //если количество букв в текущем слова больше, чем в максимальном слове, //то запоминаем текущеее слово if (count(words[i], let) > maxLetter) { wordWithMaxLetters = words[i]; maxLetter = count(wordWithMaxLetters, let); } } //если не найдено слово с буквой, то выводим not found if (wordWithMaxLetters == null) { System.out.println("No found"); } else { // иначе выводим слово System.out.println(wordWithMaxLetters); } } //заменяем все буквы, которые не letter, на пустую строчку static int count(String word, String letter) { return word.replaceAll("[^" + letter + "]", "").length(); }