Languages
[Edit]
EN

Java - find text in string

0 points
Created by:
Payne
654

In this article, we would like to show you how to find text in string in Java.

Quick solution

String string = "Dirask is awesome!";
String text = "is";

// returns true if string contains text
boolean contains = string.contains(text);
System.out.println(contains);  // true

or

String string = "Dirask is awesome!";
String text = "is";

// returns index of the first occurrence of text in string
int index = string.indexOf(text);
System.out.println(index);  // 7

 

Practical examples

1. String.contains()

In this example, we use String.contains() method to check if the string contains text.

public class Example {

    public static void main(String[] args) {
        String string = "Dirask is awesome!";
        String text = "is";

        // returns true if string contains text 
        boolean contains = string.contains(text);
        System.out.println("contains = " + contains);  // true
    }
}

Output:

contains = true

2. String.indexOf()

In this example, we use String.indexOf() method to find the index of the first occurrence of text in the string.

public class Example {

    public static void main(String[] args) {
        String string = "Dirask is awesome!";
        String text = "is";

        // returns index of the first occurrence of text in string
        int index = string.indexOf(text);
        System.out.println("index = " + index);  // 7
    }
}

Output:

index = 7

References

Alternative titles

  1. Java - how to find text in string?
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Cross technology - find text in string

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join