1

I am trying to write a method that takes a String, converts it into an Array of Strings, and then searches for a specific String within that Array. Here is my code:

public static void ThereOrNaw ( String s, String s2 ){ 

    String[] words = s.split("\\s");
    for (int i = 0; i < words.length; i++) {
        words[i] = words[i].replaceAll("[^\\w]", "");
    }
    for ( int i = 0; i < words.length; i++) {
        if( s2 == words[i] ) {
            System.out.println("Found");
        }
        else if( s2 != words[i] && (i + 1) == words.length) {
            System.out.println("Not Found");
        }
    }
}

However, when I run this method it always returns "Not Found" even if the element is in the Array. Unless, the Array of Strings has ONLY the element I am looking for. Any ideas why this isn't working?

  • 2
    Your code (and algorithm) seem over-complicated, how is your implementation supposed to differ from `System.out.println(s.contains(s2) ? "Found" : "Not Found");`? – Elliott Frisch Mar 11 '17 at 23:58
  • Elliot Frisch is correct. To add more, for case sensitive approach, `s.toLowerCase().contains(s2.toLowerCase()) ? "Found" : "Not Found"` – Pons Mar 12 '17 at 00:11

2 Answers2

0

You should use equals() not ==.

== compare your String objects not by content, but by real address in memory(in simple words). So if you will use equals() you will compare String objects by content. Also you can use equalsIgnoreCase() method if you do not care about case.

And another one little advice, check that s2 not null before you will invoke equals(), because you don't know, which object client will send to this method.

For example:

if (s2 != null && s2.equals(words[i])) { ...

else if (s2 != null && !s2.equals(words[i]) ...
Aleksandr Podkutin
  • 2,532
  • 1
  • 20
  • 31
0

Well as he said you don't have to use == comparing words, == compare objects

Look i made the change in your code for you:

 public static void main(String[] args) {

    thereOrNaw("hola","hola");
    thereOrNaw("hola","mundo");
}

public static void thereOrNaw ( String s, String s2 ){ 

    String[] words = s.split("\\s");
    for (int i = 0; i < words.length; i++) {
        words[i] = words[i].replaceAll("[^\\w]", "");
    }
    for ( int i = 0; i < words.length; i++) {
        if( s2.equals(words[i]) ) {
            System.out.println("Found");
        }
        else if( s2 != words[i] && (i + 1) == words.length) {
            System.out.println("Not Found");
        }
    }
}

And it gaves me:

Found Not Found

Yussef
  • 610
  • 6
  • 11