简体   繁体   English

Java:与String问题相比,BufferedReader行

[英]Java: BufferedReader lines compared to String issues

I have a program that is reading a text file that has a list of items, creates an ArrayList consisting of the items it reads, then compares it to a few chosen words. 我有一个程序正在读取具有项目列表的文本文件,创建一个由其读取的项目组成的ArrayList,然后将其与几个选定的单词进行比较。 For example, my text file contains this (without the numbering): 例如,我的文本文件包含以下内容(无编号):

  1. book
  2. desk
  3. food 餐饮
  4. phone 电话
  5. suit 适合

and it reads each one and adds it to an ArrayList. 然后读取每个并将其添加到ArrayList中。 When I tried comparing a String s = "book" to each element in the ArrayList, I find that s is not equal to anything. 当我尝试将String s =“ book”与ArrayList中的每个元素进行比较时,我发现s不等于任何值。 This is what I have in a method: 这是我所拥有的一种方法:

for (int i = 0; i < list.size(); i++)
{
if (s.equals(list.get(i))
    return true;
}

s.contains() doesn't work either. s.contains()也不起作用。 When I print the ArrayList, there's an additional whitespace at the end of each String element. 当我打印ArrayList时,每个String元素的末尾都有一个空白。 How can I get the comparison to work when s = "book"? 当s =“ book”时如何进行比较? Why is there additional whitespace? 为什么会有额外的空格?

You can use the trim() method of the String class to remove whitespaces in the start and the end of the string. 您可以使用String类的trim()方法删除字符串开头和结尾的空格。

The whitespaces may be in the file but you didn't notice it. 空格可能在文件中,但您没有注意到它。 Check with an editor that there are no spaces at the end. 与编辑器确认最后没有空格。 To be more sure, check with a hexadecimal editor like hd on unix. 为了更确定,请使用unix上的hd这样的十六进制编辑器进行检查。

Also, check that the read strings do not contain the line feed character. 另外,请检查读取的字符串是否不包含换行符。

Use trim() to remove leading and trailing whitespace. 使用trim()删除前导和尾随空格。

if (s.equals(list.get(i).trim())
    return true;
}

instead of 代替

if (s.equals(list.get(i))
  return true;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM