1package hello;
2
3public class SubStringProblem {
4
5 public static void main(String[] args) {
6
7 // 1st example - You can use the indexOf() method to check if
8 // a String contains another substring in Java
9 // if it does then indexOf() will return the starting index of
10 // that substring, otherwise it will return -1
11
12 System.out
13 .println("Checking if one String contains another String using indexOf() in Java");
14 String input = "Java is the best programming language";
15 boolean isPresent = input.indexOf("Java") != -1 ? true : false;
16
17 if (isPresent) {
18 System.out.println("input string: " + input);
19 System.out.println("search string: " + "Java");
20 System.out.println("does String contains substring? " + "YES");
21 }
22
23 // indexOf is case-sensitive so if you pass wrong case, you will get wrong
24 // result
25 System.out.println("Doing search with different case");
26 isPresent = input.indexOf("java") != -1 ? true : false;
27 System.out.println("isPresent: " + isPresent); // false because indeOf() is
28 // case-sensitive
29
30 // 2nd example - You can also use the contains() method to check if
31 // a String contains another String in Java or not. This method
32 // returns a boolean, true if substring is found on String, or false
33 // otherwise.
34 // if you need boolean use this method rather than indexOf()
35 System.out
36 .println("Checking if one String contains another String using contains() in Java");
37 input = "C++ is predecessor of Java";
38 boolean isFound = input.contains("Java");
39 if (isFound) {
40 System.out.println("input string: " + input);
41 System.out.println("search string: " + "Java");
42 System.out.println("does substring is found inside String? " + "YES");
43 }
44
45 // contains is also case-sensitive
46 System.out.println("Searching with different case");
47 isFound = input.contains("java");
48 System.out.println("isFound: " + isFound); // false because indeOf() is
49 // case-sensitive
50
51 }
52}
53
54Output
55Checking if one String contains another String using indexOf() in Java
56input string: Java is the best programming language
57search string: Java
58does String contain substring? YES
59Doing search with different case
60isPresent: false
61Checking if one String contains another String using contains() in Java
62input string: C++ is the predecessor of Java
63search string: Java
64does substring is found inside String? YES
65Searching for different case
66isFound: false