2

I would like to find same word in two string.

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

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

String variables:

cons,john,$,alex,manag;

String second:

ins_manages(john,cons)

As it is seen, both strings they have john and cons and I want to check if both have same char sequences or not but I don't know how it can be checked? Is there any way to check it directly?

Solution: String [] newvar; newvar = variables.split(",");

After that, I used a for loop and matched them one by one.

BR

nic
  • 125
  • 1
  • 3
  • 7

2 Answers2

5

Split both the strings and compare the individual words using foreach as shown below:

    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);
    }
Infinite Recursion
  • 6,511
  • 28
  • 39
  • 51
0

Your requirements are a little ambiguous. You're asking to find the same singular word in two strings, then your sample asks for finding two words in the same strings.

For verifying that one single word is in two strings, you can just do:

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

You can put that in a loop if you need to do it over multiple words. Again, your requirements are a little fuzzy though; if you straighten them up a more efficient solution probably exists.

John Humphreys
  • 37,047
  • 37
  • 155
  • 255
  • No, I would like to find if two different strings have the same char sequences or not. In the example, I have two different strings and in these strings I have a mutual charsequence like john. These variables can be changed that's I can't use a String word like you have in your example. – nic Aug 25 '14 at 17:37
  • Ah okay. You should provide some better examples; it's still a little unclear. Give some sample input and output. Like "If I call foo(x,y,z) with x=, y=, and z=, then I expect the following output." And give a couple different inputs. Then people will be able to answer it easier :) – John Humphreys Aug 25 '14 at 17:40