【问题标题】:Find the same word in two different strings在两个不同的字符串中查找相同的单词
【发布时间】:2014-10-18 21:57:21
【问题描述】:

我想在两个字符串中找到相同的单词。

startpoint = newresult.indexOf('\'');
endpoint = newresult.lastIndexOf('\'');

variables = newresult.substring(startpoint, endpoint);
variables = variables.replace("\r\n", ",");
variables = variables.replaceAll("'", "");`

字符串变量:

缺点,约翰,$,alex,manag;

字符串秒:

ins_manages(john,cons)

正如所见,两个字符串都有 john 和 cons,我想检查两者是否具有相同的字符序列,但我不知道如何检查?有没有办法直接查?

解决方案: String [] newvar; newvar = variables.split(",");

之后,我使用了一个 for 循环并一一匹配。

BR

【问题讨论】:

  • 你的字符串有'那个字符?
  • @Frakcool 其实我可以删除它们,我需要的只是找到字符串之间的交集。
  • 你说的是最长公共子串问题,你可以google一下。您可以使用后缀树或使用动态编程有效地做到这一点。

标签: java string match contains indexof


【解决方案1】:

您的要求有点模棱两可。您要求在两个字符串中查找相同的单数单词,然后您的示例要求在相同的字符串中查找两个单词。

要验证一个单词是否在两个字符串中,您可以这样做:

public boolean bothStringsContainWord(String s1, String s2, String word) {
    return s1.contains(word) && s2.contians(word);
}

如果您需要对多个单词执行此操作,可以将其置于循环中。同样,您的要求有点模糊;如果您将它们理顺,则可能存在更有效的解决方案。

【讨论】:

  • 不,我想知道两个不同的字符串是否具有相同的字符序列。在示例中,我有两个不同的字符串,在这些字符串中我有一个相互的字符序列,例如 john.这些变量可以更改,因为我不能像您在示例中那样使用字符串字。
  • 啊,好吧。你应该提供一些更好的例子;它仍然有点不清楚。给出一些示例输入和输出。就像“如果我用 x=、y= 和 z= 调用 foo(x,y,z),那么我期望得到以下输出。”并给出几个不同的输入。然后人们将能够更容易地回答:)
【解决方案2】:

拆分两个字符串并使用 foreach 比较单个单词,如下所示:

    String first = "hello world today";
    String second = "Yet another hello worldly day today";

    //split the second string into words
    List<String> wordsOfSecond = Arrays.asList(second.split(" "));

    //split and compare each word of the first string           
    for (String word : first.split(" ")) {
        if(wordsOfSecond.contains(word))
            System.out.println(word);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-13
    • 2014-04-17
    • 1970-01-01
    • 2023-01-26
    • 1970-01-01
    • 2016-08-30
    • 1970-01-01
    • 2019-11-07
    相关资源
    最近更新 更多