- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to check if a Substring is present in a given String
A substring is a part of a string and it can be checked if a particular substring is present in the given string or not. An example of this is given as follows −
String = The sunset is beautiful Substring = sunset
This substring is present in the string.
A program that demonstrates this is given as follows −
Example
public class Example { public static void main(String args[]) { String str = "Apples are red"; String substr = "are"; int n1 = str.length(); int n2 = substr.length(); System.out.println("String: " + str); System.out.println("Substring: " + substr); for (int i = 0; i <= n1 - n2; i++) { int j; for (j = 0; j < n2; j++) { if (str.charAt(i + j) != substr.charAt(j)) break; } if (j == n2) { System.out.println("The substring is present in the string at index " + i); return; } } System.out.println("The substring is not present in the string"); } }
Output
String: Apples are red Substring: are The substring is present in the string at index 7
Now let us understand the above program.
First, the string and substring are printed. The code snippet that demonstrates this is given as follows −
String str = "Apples are red"; String substr = "are"; int n1 = str.length(); int n2 = substr.length(); System.out.println("String: " + str); System.out.println("Substring: " + substr);
Then a for loop is used to find if the substring is a part of the given string or not. If it is, then this is printed and the index at which the substring starts in the string is also specified. Then the main() function returns. The code snippet that demonstrates this is given as follows −
for (int i = 0; i <= n1 - n2; i++) { int j; for (j = 0; j < n2; j++) { if (str.charAt(i + j) != substr.charAt(j)) break; } if (j == n2) { System.out.println("The substring is present in the string at index " + i); return; } } }
If the substring is not present in the string, then this is printed after the finishing of the for loop. The code snippet that demonstrates this is given as follows −
System.out.println("The substring is not present in the string");