我必须检查File1中的单词是否存在于File2中,然后进行计数。这两个文件中的数据如下所示。String.contains函数不起作用
File1中的字被如下所示:
- 发表
- 发愁
- 发达
- 发抖
- 发挥
在文件2的数据被如下所示:
- 这篇论文是什么时候发表的?
- 91。数据删掉被马工程师了
- 92。驾驶酒后很大危害
- 93。客观地要他人评价
- 94 。我不小心水壶打翻了把
我写的代码如下:
File file1 = new File("ChineseWord.txt");
Scanner sc = new Scanner(new FileInputStream(file1));
ArrayList<String> list = new ArrayList<String>();
ArrayList<String> newList = new ArrayList<String>();
while(sc.hasNext()){
list.add(sc.next());
}
sc.close();
File file2 = new File("RandomData.txt");
Scanner newScanner = new Scanner(new FileInputStream(file2));
int count = 0;
for (int i = 0; i < list.size(); i++) {
while(newScanner.hasNext()){
String word = newScanner.nextLine();
String toMatch = list.get(i);
if(word.contains(toMatch)){
System.out.println("Success");
count++;
}
}
String test = list.get(i);
newList.add(test+"exists" + count+ "times");
count =0;
}
问题是它对所有单词都返回0,而File1中的第一个单词存在于File2的第一行。如果我手动做这样的事情
if(word.contains("发表")){
System.out.println("Success");
count++;
}
它打印成功,否则它不会?这是为什么?
见http://stackoverflow.com/questions/22048692/check-if-string-contains-cjk-chinese-characters and http://stackoverflow.com/questions/26357938/detect-chinese-character-in-java – Adi
我会确保字符编码读取是您写的。您可以尝试使用UTF-8或UTF-16LE,但必须保持一致。 –
字符编码是UTF-8 – indexOutOfBounds