Answer:
public class Solution {
public static void main(String args[]) {
String[] allNames = new String[]{"Bob Smith", "Elroy Jetson", "Christina Johnson", "Rachael Baker", "cHRis", "Chris Conly"};
String searchString = "cHRis";
findNames(allNames, searchString);
}
public static void findNames(String[] listOfName, String nameToFind){
ArrayList<String> resultName = new ArrayList<String>();
for(String name : listOfName){
if (name.toLowerCase().contains(nameToFind.toLowerCase())){
resultName.add(name);
}
}
for(String result : resultName){
System.out.println(result);
}
}
}
Explanation:
The class was created called Solution. The second line define the main function. Inside the main function; we initialized and assign an array called allNames to hold the list of all name. Then a String called searchString was also defined. The searchString is the string to search for in each element of allNames array. The two variables (allNames and searchString) are passed as argument to the findNames method when it is called.
The method findNames is defined and it accept two parameters, an array containing list of names and the name to search for.
Inside the findNames method, we initialized and assigned an ArrayList called resultName. The resultName variable is to hold list of element found that contain the searchString.
The first for-loop goes through the elements in the allNames array and compare it with the searchString. If any element is found containing the searchString; it is added to the resultName variable.
The second for-loop goes through the elements of the resultName array and output it. The output is empty if no element was found added to the resultName variable.
During comparison, the both string were converted to lower case before the comparison because same lowercase character does not equal same uppercase character. For instance 'A' is not same as 'a'.