Finding a String Within Another String

suggest change

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Strings:
* Finding a String Within Another String

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap