gpt4 book ai didi

java - 即使字符串看起来相同, String.contains(astring) 也不返回 true

转载 作者:行者123 更新时间:2023-12-01 21:48:59 25 4
gpt4 key购买 nike

所以我正在开发一个程序,用于根据 CSV 文件中的位置格式化和查询 google 的纬度和经度坐标。该程序绝不是高效的,老实说,我不在乎,只要它能够正确地格式化输出,以便我可以将其用于 XML 文件即可。谷歌对查询有限制,所以我决定将以前的查询存储在一个基本文本文件中,然后使用缓冲区读取器检查是否 line.contains(companyname) 但它从不匹配。我打印出与 contains 和行进行比较的字符串,它们在打印输出中是相同的,但长度相差 1。我假设有一些隐藏字符或 contains() 方法抛出的内容。

示例输出:

enter image description here

以下是此过程的两个重要方法。

public static void writeCordFile(String company, String lat, String log) {
try {
System.out.println("writing to /Users/ASheridan/Downloads/cord" +"data:"+company + "lat: " + lat + "log" + log);
FileWriter writer = new FileWriter("/Users/ASheridan/Downloads/cord", true);


//writer.write(company + " lat: " + lat + " log: " + log);
writer.write(company+" ");
writer.write("\r\n");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}





}


public static boolean checkIfCordinatesExist(String companyName) {
BufferedReader br = null;
String cordStorage = "/Users/ASheridan/Downloads/cord";
String lineCord = "";
try {

br = new BufferedReader(new FileReader(cordStorage));
System.out.println("CHECKING THE FULL FILE FOR MATCHES");
int i=0;
while ((lineCord = br.readLine()) != null) {

System.out.println(i);
i++;
System.out.println("compare to: "+lineCord.compareTo(companyName));
System.out.println("line length: "+lineCord.length());
System.out.println("company length: "+companyName.length());
if (lineCord.toLowerCase().contains(companyName.toLowerCase())) {
System.out.println("Existing Cordinates for " + cordStorage + " found");
return true;
}

else {
System.out.println("Result for " + companyName +"not found in line:" + lineCord);
}



}

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

return false;
}

最佳答案

答案实际上就在您的打印语句中。

System.out.println("Result for " + companyName +"not found in line:" + lineCord);

在一行上打印“...的结果”,并将其余内容打印在下一行上。考虑到您没有使用 printf,可以推断 companyName 末尾有 '\n' 字符。因此 print 会超过两行。正如您所注意到的,字符串的长度相差 1,这再次表明 companyName 变量可能包含该换行符。请引用this回答如何删除换行符。

关于java - 即使字符串看起来相同, String.contains(astring) 也不返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35489596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com