如何删除重复的字符串?

时间:2017-01-27 04:49:23

标签: java string file

在我的代码中,我的驱动器中有两个文件,这两个文件有一些文本,我想在控制台中显示这些字符串,并删除重复的字符串并显示重复的字符串一次,而不是显示两次。

代码:

public class read {
public static void main(String[] args) {
    try{
        File file = new File("D:\\file1.txt");
        FileReader fileReader = new FileReader(file);
        BufferedReader br = new BufferedReader(fileReader);
        StringBuffer stringBuffer = new StringBuffer();
        String line;
        while((line = br.readLine()) != null){
            stringBuffer.append(line);
            stringBuffer.append("\n");
        }
        fileReader.close();
        System.out.println("Contents of file1:");
        String first = stringBuffer.toString();
        System.out.println(first);

        File file1 = new File("D:\\file2.txt");
        FileReader fileReader1 = new FileReader(file1);
        BufferedReader br1 = new BufferedReader(fileReader1);
        StringBuffer stringBuffer1 = new StringBuffer();
        String line1;
        while((line1 = br1.readLine()) != null){
            stringBuffer1.append(line1);
            stringBuffer1.append("\n");
        }
        fileReader1.close();
        System.out.println("Contents of file2:");
        String second = stringBuffer1.toString();
        System.out.println(second);

        System.out.println("answer:");
        System.out.println(first+second);

    }catch (IOException e) {
        // TODO: handle exception
        e.printStackTrace();
    }
}
}

输出是:

answer:
hi hello
how are you
hi ya
i am fine

但我想比较两个字符串,如果重复相同的字符串,那么该字符串应该显示一次。

我期望的输出是这样的:

answer:
hi hello
how are you
ya
i am fine

在两个字符串中都找到“hi”,这样我就需要删除一个重复的字符串。 我该怎么办,请帮忙。 提前谢谢。

1 个答案:

答案 0 :(得分:1)

您可以通过此方法传递您的行以解析出重复的单词:

// store unique previous words
static Set<String> words = new HashSet<>();

static String removeDuplicateWords(String line) {
    StringJoiner sj = new StringJoiner(" ");
    // split on whitespace to get distinct words
    for (String word : line.split("\\s+")) {
        // try to add word to the set
        if (words.add(word)) {
            // if the word was added (=not seen before), append to the result
            sj.add(word);
        }
    }
    return sj.toString();
}