Java Language Strings Finding a String Within Another String

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

To check whether a particular String a is being contained in a String b or not, we can use the method String.contains() with the following syntax:

b.contains(a); // Return true if a is contained in b, false otherwise

The String.contains() method can be used to verify if a CharSequence can be found in the String. The method looks for the String a in the String b in a case-sensitive way.

String str1 = "Hello World";
String str2 = "Hello";
String str3 = "helLO";

System.out.println(str1.contains(str2)); //prints true
System.out.println(str1.contains(str3)); //prints false

Live Demo on Ideone


To find the exact position where a String starts within another String, use String.indexOf():

String s = "this is a long sentence";
int i = s.indexOf('i');    // the first 'i' in String is at index 2
int j = s.indexOf("long"); // the index of the first occurrence of "long" in s is 10
int k = s.indexOf('z');    // k is -1 because 'z' was not found in String s
int h = s.indexOf("LoNg"); // h is -1 because "LoNg" was not found in String s

Live Demo on Ideone

The String.indexOf() method returns the first index of a char or String in another String. The method returns -1 if it is not found.

Note: The String.indexOf() method is case sensitive.

Example of search ignoring the case:

String str1 = "Hello World";
String str2 = "wOr";
str1.indexOf(str2);                               // -1
str1.toLowerCase().contains(str2.toLowerCase());  // true
str1.toLowerCase().indexOf(str2.toLowerCase());   // 6

Live Demo on Ideone



Got any Java Language Question?