Searching characters and substring in a String in Java



Following is the Java program to search characters and substring in a string βˆ’

Example

 Live Demo

import java.io.*;
import java.lang.*;
public class Demo {
   public static void main (String[] args) {
      String test_str = "Hello";
      CharSequence seq = "He";
      boolean bool_1 = test_str.contains(seq);
      System.out.println("Was the substring found? " + bool_1);
      boolean bool_2 = test_str.contains("Lo");
      System.out.println("Was the substring found? " + bool_2);
   }
}

Output

Was the substring found? true
Was the substring found? False

A class named Demo contains the main function. Here, a string is defined, and a CharSequence instance is created. The β€˜contains’ function associated with the string is used to check if the original string contains the specific substring. It is then printed on the screen.

Updated on: 2020-09-14T08:44:41+05:30

644 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements