首页 > 解决方案 > 不确定我的字符串代码是否区分大小写

问题描述

对于包含文本的行数,我一直得到不正确的答案。我相信我的代码忽略了标点符号(例如,它不会检测到)和大写变体(如(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

标签: java

解决方案


标点符号被计算在内,但混合大小写不被计算在内。最简单的解决方法是改变

if (sentence.contains(search_word))

if (sentence.toLowerCase().contains(search_word.toLowerCase()))

search_word在循环之前转换为小写一次会更好。


推荐阅读