Write a Java program to check whether a substring(abc) appears before a period(.) within a given string
Question
Write a Java program to check whether a substring (abc) appears before a period (.) within a given string
Solution
Here is a simple Java program that checks if the substring "abc" appears before a period (.) in a given string:
import java.util.Scanner;
public class SubstringBeforePeriod {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input a string from the user
System.out.print("Enter a string: ");
String input = scanner.nextLine();
// Call the method to check the condition
boolean result = isSubstringBeforePeriod(input, "abc");
// Output the result
if (result) {
System.out.println("The substring 'abc' appears before a period (.) in the given string.");
} else {
System.out.println("The substring 'abc' does not appear before a period (.) in the given string.");
}
scanner.close();
}
// Method to check if the substring appears before the period
public static boolean isSubstringBeforePeriod(String str, String substr) {
int periodIndex = str.indexOf('.');
int substrIndex = str.indexOf(substr);
// Check if the substring appears before the period
return (substrIndex != -1) && (periodIndex != -1) && (substrIndex < periodIndex);
}
}
Explanation of the Program
- Input Handling: The program prompts the user to enter a string.
- Method Logic: The method
isSubstringBeforePeriod
checks the positions of the substring "abc" and the first period in the string. - Condition Check: It verifies if the substring occurs before the period and returns a boolean value.
- Output: The program then displays whether the substring appears before the period based on the returned value.
You can run this program in any Java environment to test it with various strings.
Similar Questions
Which method is used to check if a string starts with a specific substring in Java?Question 2Answera.startsWith()b.beginsWith()c.firstWith()d.initiateWith()
Longest Substring Without Repeating CharactersGiven a string s find the length of the longest substring without repeating characters.
Given a string A and two integer B and C.Find and return the substring of A starting from index B and ending with index C.
Write a java program to accept a String and the perform the following operations:a) Count the number of words with the first and the last letter being same.
Write a Java program to find the smallest window in a string containing all characters of another string.
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.