Find Substring of a String in Java
Here you will learn, that how to find the substring of a string in Java programming with example.
We will check if the sub-string is present in the sentence. If exists, it will display the index location, if not it will display a message as “Sub-string does not Exist in the sentence”.
Program to find the Substring of a String in java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import java.util.*; public class SubstringsOfAstring { public static void main(String []args) { String str,substr; Scanner in = new Scanner(System.in); System.out.print("Enter a sentence : "); str = in.nextLine(); System.out.print("Enter a string to find: "); substr = in.nextLine(); int index = str.indexOf(substr); if(index==-1) { System.out.println("Substring not Exist in the sentence"); } else { index++; System.out.println("Substring is avaliable at "+index+" index position"); } } } |
Output
Check out our other Java Programming Examples