我有一个方法可以在文件中搜索您提供的字符串并返回一个计数。但是我在区分大小写方面遇到了麻烦。方法如下:
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;
}
我将它解析为要在文件中搜索的字符串数组。但是,需要搜索数组中的某些字符串以忽略大小写。我怎么能改变我的方法来适应这个,因为我完全被难住了。
这个方法被多个类使用,所以我不能简单地在 for 循环中插入一个 if 语句来表示
if(i == 4) ...
... strLine.toLowerCase().contains(searchFor[i].toLowerCase()) ...
关于如何更好地实现此功能有什么想法吗?
谢谢, 约旦
最佳答案
为什么不在方法参数中添加一个boolean ignoreCase
?
或者您可以重载方法。
public int[] count(String[] searchFor, String fileName, boolean ignoreCase) {}
关于Java 字符串查找器 - 如何切换区分大小写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27275147/