"In" and "Not In" in Java [Duplicate]

I'm new in java and I was wonder if there is a way to check one string against another string, I've done it in Python like this"

text = "Tree"
if "re" in text:
    print "yes, there is re exist in Tree"

do we have such way in java to check one sting if exist in another string?

Edit: I used String as an example, i was mainly looking for such function like how python has, as i mention in my caption "in" and "not in" in java, to compare any variable that exist within another variables.

in python i can compare array or list vs single String variable:

myList = ["Apple", "Tree"]
if "Apple" in myList:
    print "yes, Apple exist"

even array vs array:

myList = ["Apple", "Tree","Seed"]
if ["Apple","Seed"] in myList:
    print "yes, there is Apple and Seed in your list"

and single Integer vs array:

myNumber = [10, 5, 3]
if 10 in myNumber:
    print "yes, There is 10"

I was mainly looking for function that if java provide so it can speed up the variables comparison.

2

String#contains is what you are looking for.

String text = "Tree";
if (text.contains("re")) {
    System.out.println("yes, there is re exist in Tree");
}

Alternatives:

String#indexOf

String text = "Tree";
if (text.indexOf("re") != -1) {
    System.out.println("yes, there is re exist in Tree");
}

String#matches

String text = "Tree";
if (text.matches(".*re.*")) {
    System.out.println("yes, there is re exist in Tree");
}

Pattern

String text = "Tree";
if (Pattern.compile(".*re.*").matcher(text).find()) {
    System.out.println("yes, there is re exist in Tree");
}
2

There is:

boolean isInString = fullString.contains(subString);

Update for new question:

If you want to check if string is in given array, you have Arrays class for that:

Arrays.asList(givenArrayOfStrings).contains(yourString)

Note: for your specific created objects, you must implement method equals() in order to use this.

You can have at least 2 ways to do that in java:

public static void main(String[] args) {
    String text = "Tree";

    // option 1: index of... returns -1 if not present
    System.out.println(text.indexOf("re"));

    // option 2: contains
    System.out.println(text.contains("re"));
}

Simple way of doing this in java as follows

class StringTest { // Class
    public static void main(String[] args) { // Main method
        String text = "Tree";
        if (text.contains("re")) { // Checking
            System.out.println("yes, there is re exist in Tree");
        }
    }
}

You can simply check this using the contains() method of the String class.

String s = "answer";
if(s.contains("ans")) {
    System.out.print("Yes");
}
Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest