James
James

Reputation: 77

Finding and comparing words in a single string. Java

If I am looking for two words in a string. How would I go about it?

For example, the string "asdgcatgadfdog" contains cat and dog. How would I go about looking for these words in a string, and then printing true if it finds both?

It cant be string.startsWith because it doesn't start with it, and I don't think it's contains. Or at least, I haven't been able to make it work with contains.

A push in the right direction is all I'm looking for.

Upvotes: 0

Views: 98

Answers (6)

Kylo Zhang
Kylo Zhang

Reputation: 34

You can use indexOf() or contains(). In fact, the contains() is calling the indexOf():

public boolean contains(CharSequence s) {
    return indexOf(s.toString()) > -1;
}  

Check the following code:

String str1 = "lsjfcatsldkjglsdog";
String str2 = "lsjfjlsdjsldkjglsdog";
System.out.println("contains:");
System.out.println("str1: "
        + (str1.contains("cat") && str1.contains("dog")));
System.out.println("str2: "
        + (str2.contains("cat") && str2.contains("dog")));
System.out.println("indexOf:");
System.out.println("str1: "
        + (str1.indexOf("cat") > -1 && str1.indexOf("dog") > -1));
System.out.println("str2: "
        + (str2.indexOf("cat") > -1 && str2.indexOf("dog") > -1));

The output is:

contains:
str1: true
str2: false
indexOf:
str1: true
str2: false

Upvotes: 0

Eng.Fouad
Eng.Fouad

Reputation: 117587

You can use a regular expression:

boolean found = "asdgcatgadfdog".matches("(?i).*(cat.*dog)|(dog.*cat).*");

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172428

Try this:

String str= "asdgcatgadfdog";
if(str.contains("cat") && str.contains("dog")){
    System.out.println("Match");
}

Upvotes: 0

HJK
HJK

Reputation: 1382

public static void main(String[] args) {
String str = "asdgcatgadfdog";
if(str.indexOf("cat")!= -1 && str.indexOf("dog")!= -1){
    System.out.println("true");
}else{
    System.out.println("false");
}
}

Upvotes: 1

GAgarwal
GAgarwal

Reputation: 122

Check the below code:

public static void main(String[] args) {
    String word = "asdgcatgadfdog";
    if(word.contains("cat")){
        System.out.println("true");
    }
}

Upvotes: 1

sriman reddy
sriman reddy

Reputation: 773

boolean match = str1.toLowerCase().contains(str2.toLowerCase())

Upvotes: 0

Related Questions