我有两个String,需要与单词进行比较

时间:2018-07-06 07:37:48

标签: java core

String first-word="they will win";

String second-word="will they";

String[] spiltfirstWord= firstWord.split("\\s+");

String[] spiltsecondWord= secondWord.split("\\s+");

我尝试拆分字符串,但对我而言,阻止因素是单词在不同的索引处。

在输出中,我需要打印“ win”

4 个答案:

答案 0 :(得分:2)

我建议您使用exportType: new sap.ui.core.util.ExportTypeCSV({ separatorChar: "\t" , mimeType: "application/vnd.ms-excel" , charset: "utf-8", fileExtension: "xls" }),而不是数组,它可以在任何角度简化您的生活。

使用此代码,您可以实现目标

List<String>

输出:

  

[win]

PS:您可以用Java 8 Lambda代替cicle

    String firstWord="they will win";
    String secondWord="will they";

    List<String> firstList = Arrays.asList(firstWord.split("\\s+"));
    List<String> secondList = Arrays.asList(secondWord.split("\\s+"));
    List<String> result = new ArrayList<>();

    for( String word : firstList){
        if(!secondList.contains(word)){
            result.add(word);
        }
    }

    System.out.println(result);

答案 1 :(得分:0)

您应该将第一个String映射到String数组中,将另一个String映射到String Set中。这样可以简化匹配操作并提高效率。

它将给出这样的逻辑:

String firstWord = "they will win";
String secondWord = "will they";

Set<String> splitsecondWord = Arrays.stream(secondWord.split("\\s+"))
                                    .collect(Collectors.toSet());

List<String> missingWords = Arrays.stream(firstWord.split("\\s+"))
                                .filter(s -> !splitsecondWord.contains(s))
                                .collect(Collectors.toList());

System.out.println(missingWords);

输出:

  

[win]

答案 2 :(得分:0)

使用Patternstream的另一种可能的解决方案

    Pattern splitter = Pattern.compile("\\s+");
    String firstWord = "they will win";
    String secondWord = "will they";
    List<String> secondWordList = splitter.splitAsStream(secondWord).collect(Collectors.toList());

    splitter.splitAsStream(firstWord)
            .filter(w -> !secondWordList.contains(w))
            .forEach(System.out::println);

答案 3 :(得分:0)

在这里您可以做得非常简单

 String firstword = "they will win one day";
        String secondword = "will they";
        List<String> diff = Arrays.stream(firstword.split("\\s+")).filter(s -> !secondword.contains(s))
                .collect(Collectors.toList());
System.out.println(diff); // output [win, one, day]