java - 从文件读取时的 String.contains()

标签 java string

我正在逐行读取文件,然后我想检查该字符串是否包含另一个字符串,所以我使用 String.contains方法,但它始终返回 false。

我尝试拆分输入行(然后使用 String.containsString.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/

相关文章:

java - 返回给定整数的位数的递归方法

java - 我可以在java中将一维数组存储到二维数组中吗?

java - ArrayList<对象> 到 ArrayList<字符串>

Java打印数组中的某些字符

windows - 使用批处理删除文件夹中除列表中文件之外的所有文件

c++ - 我无法在我的 if 语句中识别 endl 字符\n

java - 使用 Java 中的任何替代 DataStructure 优化 Nested-if

java - 混合两个通用列表java

java - 调用 findValue 方法时 JsonNode 返回 null?

.net - 如何重新排列字符串中的字符?