java - 不确定我的字符串代码是否区分大小写
问题描述
对于包含文本的行数,我一直得到不正确的答案。我相信我的代码忽略了标点符号(例如,它不会检测到)和大写变体(如(The))。
例如,如果一个文件包含 5268 行,其中 1137 行包含单词“the”,我的代码返回输出说它只包含 1032 行包含单词“the”。
谢谢你。代码如下
while((sentence=buffer.readLine()) != null) //Reading Content from the file till the end of file
{
if (sentence.contains(search_word))
{
word_line_count++;
}
line_count++; //increment line count for every while loop iteration
}
System.out.println(file_name + " has " + line_count + " lines"); //printing the line count
System.out.println("Enter some text");
System.out.println( word_line_count + " line(s) contain " + "\"" + search_word + "\""); //printing the number of lines contains the given word
file_object.close(); //closing file object
解决方案
标点符号被计算在内,但混合大小写不被计算在内。最简单的解决方法是改变
if (sentence.contains(search_word))
至
if (sentence.toLowerCase().contains(search_word.toLowerCase()))
search_word
在循环之前转换为小写一次会更好。
推荐阅读
- javascript - CodeIgniter file upload error “You did not select a file to upload” using Ajax
- mysql - 是否可以从我的网站中获取数据,该网站在我的系统中的简单 mysql 数据库中存在?
- r - 从 json 中取消嵌套多个列
- javascript - VueJS 3-模板/ v-for中的子字符串/截断?
- c++ - C++ 中的内存更改检测功能无法正确检测某些恶意软件
- android - Java Android Studio 布局 - ImageButton 位置与 xml 背景一致
- python - Python regular expression for extracting html tags beginning with a number
- html - 带输入的角异步管道
- c - 得到错误的平方根估计
- javascript - Javascript 初学者问题:Bool 还是 Int?