Program Title: Java Program Using indexOf Command
Purpose: To demonstrate the use of the indexOf method in Java for finding the position of a substring within a string.
Inputs: A main string and a substring entered by the user.
Outputs: The position of the first occurrence of the substring in the main string or a message if the substring is not found.
Key Features:
indexOf method.
1. Start
2. Prompt the user to input the main string.
3. Prompt the user to input the substring to search for.
4. Use the `indexOf` method on the main string to find the substring's position.
5. If `indexOf` returns a value >= 0, display the position to the user.
6. If `indexOf` returns -1, display a "not found" message.
7. End
import java.util.Scanner;
public class IndexOfExample {
public static void main(String[] args) {
// Create a scanner object for input
Scanner scanner = new Scanner(System.in);
// Step 2: Prompt the user for the main string
System.out.println("Enter the main string:");
String mainString = scanner.nextLine();
// Step 3: Prompt the user for the substring
System.out.println("Enter the substring to search for:");
String subString = scanner.nextLine();
// Step 4: Use the indexOf method
int position = mainString.indexOf(subString);
// Step 5 & 6: Check if the substring is found
if (position >= 0) {
System.out.println("The substring "" + subString + "" is found at position: " + position);
} else {
System.out.println("The substring "" + subString + "" was not found in the main string.");
}
// Close the scanner
scanner.close();
}
}
Input:
Main string: Hello, welcome to the Java world!
Substring: Java
Output:
The substring "Java" is found at position: 18
Input:
Main string: Hello, welcome to the Java world!
Substring: Python
Output:
The substring "Python" was not found in the main string.