English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java array

Java object-oriented (I)

Java object-oriented (II)

Java object-oriented (III)

Java Exception Handling

Java list (List)

Java Queue (queue)

Java Map collection

Java Set collection

Java input output (I/O)

Java Reader/Writer

Java other topics

Java program to check if a string contains a substring

    Java Examples Comprehensive

In this example, we will learn to use the contains() and indexOf() methods in Java to check if a string contains a substring.

To understand this example, you should know the followingJava programmingTopic:

Example1: Check if a substring is contained in a string using contains()

class Main {
  public static void main(String[] args) {
    //Create a string
    String txt = "This is w"3codebox";
    String str1 = "w3codebox";
    String str2 = "Programming";
    //Check if the name exists in txt
    //Using contains()
    boolean result = txt.contains(str1);
    if(result) {
      System.out.println(str1 + " is present in the string.");
    }
    else {
      System.out.println(str1 + " is not present in the string.");
    }
    result = txt.contains(str2);
    if(result) {
      System.out.println(str2 + " is present in the string.");
    }
    else {
      System.out.println(str2 + " is not present in the string.");
    }
  }
}

Output Results

w3codebox is present in the string.
Programming is not present in the string.

In the above example, we have three strings txt, str1and str2. Here, we use the String'scontains()Method to check if the string str1and str2Whether it appears in txt.

Example2: Check if a substring is contained in a string using indexOf()

class Main {
  public static void main(String[] args) {
    //Create a string
    String txt = "This is w"3codebox";
    String str1 = "w3codebox";
    String str2 = "Programming";
    //Check str1whether it exists in txt
    //Using indexOf()
    int result = txt.indexOf(str1);
    if(result == -1) {
      System.out.println(str1 + " is not present in the string.");
    }
    else {
      System.out.println(str1 + " is present in the string.");
    }
    //Check str2whether it exists in txt
    //Using indexOf()
    result = txt.indexOf(str2);
    if(result == -1) {
      System.out.println(str2 + " is not present in the string.");
    }
    else {
      System.out.println(str2 + " is present in the string.");
    }
  }
}

Output Results

w3codebox is present in the string.
Programming is not present in the string.

In this example, we useString indexOf()method to find the string str1and str2In the position of txt. If the string is found, return the position of the string. Otherwise, return-1.

Java Examples Comprehensive