Java program to find if a substring exist in a user input string or not

Java program to find substring in a user input string :

In this Java program, we will learn how to find one substring in a string. The user will first enter the string and then he will enter the substring . Our program will check if it exist in the string or not. If yes, it will print the index of the substring. Let’s take a look at the program first :

Java program :

import java.util.*;

public class Main {

    public static void main(String[] args) {
        //1
        Scanner scanner = new Scanner(System.in);
        String inputString;
        String subString;

        //2
        System.out.println("Enter a string : ");
        inputString = scanner.nextLine();

        //3
        System.out.println("Enter a substring to find in the string : ");
        subString = scanner.next();

        //4
        int index = inputString.indexOf(subString);

        //5
        if (index != -1) {
            System.out.println("Index of this word : " + index);
        } else {
            System.out.println("The input sub-string is not found in the string.");
        }

    }

}

Explanation :

The commented numbers in the above program denote the step numbers below :

1. Create one Scanner object to read all user inputs.Create string inputString to read and store the user input string and subString to store the sub-string.
2. Ask the user to enter a string. Read it and store it in inputString variable.
3. Ask the user to enter a substring. Read it and store it in subString variable.
4. Find out the first index of occurance of subString in inputString. If it is found , indexOf() will return the index number. Else, it will return -1.
5. Check the value of index and print out the index if found. Else print that no sub string was found.

Sample Output :

Enter a string : 
Hello world
Enter a substring to find in the string : 
world
Index of this word : 6

Enter a string : 
Hello world
Enter a substring to find in the string : 
earth
The input sub-string is not found in the string.

Leave a Reply