Java string finder – how do I switch case sensitivity?
I have a method to search the file for the string you give it and return a count But I have a case sensitivity problem This is the method:
public int[] count(String[] searchFor,String fileName) { int[] counts = new int[searchFor.length]; try { FileInputStream fstream = new FileInputStream(fileName); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { for (int i = 0; i < searchFor.length; i++) { if (strLine.contains(searchFor[i])) { counts[i]++; } } } in.close(); } catch (Exception e) {// Catch exception if any System.err.println("Error: " + e.getMessage()); } return counts; }
I parsed an array of strings to search for files However, some strings in the array need to be searched to ignore case How can I change my way to adapt to this, because I'm completely baffled
This method is used by multiple classes, so I can't simply insert an IF statement into the for loop
if(i == 4) ... ... strLine.toLowerCase().contains(searchFor[i].toLowerCase()) ...
Any ideas on how to better implement this feature?
Thank you, Jordan
Solution
Since you have a string array in which entries need to be treated differently (for example, case sensitive and case insensitive), I suggest using case settings to create your own class for search terms:
public class SearchTerm { private final String term; private final boolean caseSensitive; public SearchTerm(final String term,final boolean caseSensitive) { this.term = term; this.caseSensitive = caseSensitive; } public String getTerm() { return term; } public boolean isCaseSensitive() { return caseSensitive; } }
You can then replace the current array with this class:
count(SearchTerm[] searchFor,String fileName)
And use it in your search method:
for (int i = 0; i < searchFor.length; i++) { if (searchFor[i].isCaseSensitive()) { if (strLine.contains(searchFor[i].getTerm())) { counts[i]++; } } else { // this line was "borrowed" from Maroun Marouns answer (you can also use different methods to search case insensitive) if (Pattern.compile(strLine,Pattern.CASE_INSENSITIVE).matcher(searchFor[i].getTerm()).find()) { counts[i]++; } } }
This way you can avoid "global" case sensitive or case insensitive searches and treat each search term differently