我正在逐行读取文件,然后我想检查该字符串是否包含另一个字符串,所以我使用 String.contains
方法,但它始终返回 false。
我尝试拆分输入行(然后使用 String.contains
或 String.equals
),因为要检查的单词是行的第一个。
我要检查的字符串是<now>
并进行拆分我注意到即使该行包含它我也会出错。
奇怪的是字符串打印正确但它的长度大于字符串<now>
(即使我使用替换来确保没有空格)我想那是我的问题。我认为这取决于文件的编码,但如果是这样,有什么解决办法吗?
该文件是另一个程序(Praat)的输出,所以我不能用其他方式保存它。
line = inFile2.nextLine();
String[] w = line.split("[\t\\s]");
String checking = w[0];
checking.replace(" ","");
checking.replace("/t","");
String st ="<now>";
System.out.println(!checking.equals(st)); //returns always true
System.out.println(st.length()); //returns 5
System.out.println(checking.length()); //returns 11
System.out.println(checking); //it prints <now> correctly
输入的字符串如下:<now> 236 62 elena information-relation
最佳答案
字符串是 immutable :
Note: The String class is immutable, so that once it is created a String object cannot be changed. The String class has a number of methods, some of which will be discussed below, that appear to modify strings. Since strings are immutable, what these methods really do is create and return a new string that contains the result of the operation.
所以应该是:
Checking = Checking.replace(" ","");
Checking = Checking.replace("/t","");
或者更好(method chaining):
Checking = Checking.replace(" ","").replace("/t","");
另请尊重naming conventions .
关于java - 从文件读取时的 String.contains(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19977514/