Vartan Vartan - 8 days ago 5
Java Question

How to count mutual words in 2 strings in Java?

Say I have two strings:

String s1 = "My name is Alex."

String s2 = "My name is Nick."


I want the program to count mutual words and return the value. With those strings, the returned value would be 3, because of the 3 words both have in common: my, name, is. For some reason, in my program, the num value returned is always 0.

public static int sameWord(String s1, String s2) {

int num = 0;
String[] a = s1.split(" ");
String[] b = s2.split(" ");

for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++) {
if (a[i] == b[j]) {
num++;
}
}
}

return num;
}

Answer

As jackarms said, you are using == to compare strings where you should be using .equals. See this.

Try

  int num = 0;
  String[] a = s1.split(" ");
  String[] b = s2.split(" ");

  for (int i = 0; i < a.length; i++) {
      for (int j = 0; j < b.length; j++) {
          if (a[i].equals(b[j])) {
              num++;
          }
      }
  }

  return num;