【问题标题】:Is using the .contains function to include spaces possible?是否使用 .contains 函数来包含空格?
【发布时间】:2015-02-07 16:33:52
【问题描述】:

这是我的场景。

我正在文本文件中搜索一行,但我没有给它完全匹配,所以我使用 .contains() 函数来检查只包含字符串的行,但它会忽略空格。

例如,如果我在包含

的文件中搜索“无法忍受的相似”
"The Dark Knight"
"The First Ones"
"The Unbearable Likeness Of Being"

然后它只是返回第一行,因为它忽略了空格。有没有办法让它识别空间?

【问题讨论】:

  • 你说的是哪个空间?
  • 我不明白你的例子。为什么它会返回第一行?你说的是哪个空间?
  • 你的密码是什么?您是否使用 for 循环遍历 string[] 数组中的所有行?
  • 我正在使用 while 循环。如果我搜索“The Unbearable Likeness”,它会返回包含“the”的第一行。
  • 与其谈论关于你的代码,不如在你的问题中展示它?

标签: java string filereader


【解决方案1】:

contains() 方法不排除空格或类似的东西。仅当包含整个字符串时才返回 true。很容易演示:

System.out.println("Fred Bloggs".contains("red"));
System.out.println("Fred Bloggs".contains("Fred Bloggs"));
System.out.println("Fred Bloggs".contains("Fred Bloggs II"));
System.out.println("Fred Bloggs".contains("Fred Blags"));

打印:

true
true
false
false

对于您的情况,for 循环可能会起作用:

String searchString = "The Unbearable Likeness";

String content = new String(Files.readAllBytes(Paths.get("titles.txt")), "UTF-8");
String[] titles = content.split("[\r\n]");
for (String title: titles) {
    if (title.contains(searchString)) {
        System.out.print("Found match: " + title);
    }
}

这会从文件titles.txt 中加载标题,分成几行,遍历它们并在标题包含搜索字符串时打印一条消息。

【讨论】:

    猜你喜欢
    • 2019-05-29
    • 2020-12-27
    • 2022-12-15
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-03
    相关资源
    最近更新 更多