Java: Check whether a substring appears before a period(.) within a given string
Java String: Exercise-73 with Solution
Write a Java program to check whether a substring appears before a period(.) within a given string.
Visual Presentation:
Sample Solution:
Java Code:
import java.util.*;
// Define a class named Main
public class Main {
// Method to check if 'abc' appears before a period in the given string
public Boolean abcBeforePeriod(String stng) {
int len = stng.length(); // Get the length of the input string
String abc = "abc"; // Create a string variable 'abc' to match against
Boolean match = false; // Initialize a boolean variable 'match' to false
if (len < 3)
return false; // If the length of the string is less than 3, return false as 'abc' cannot appear
for (int i = 0; i < len - 2; i++) {
// Extract a substring of length 3 starting from the current index 'i'
String temp = stng.substring(i, i + 3);
// Check if the extracted substring matches 'abc' and it's at the beginning of the string
if (temp.compareTo(abc) == 0 && i == 0)
match = true;
// Check if the extracted substring matches 'abc' and the character before it is not a period ('.')
else if (temp.compareTo(abc) == 0 && stng.charAt(i - 1) != 46)
match = true;
}
return match; // Return the boolean variable indicating if 'abc' appeared before a period
}
// Main method to execute the program
public static void main(String[] args) {
Main m = new Main(); // Create an instance of the Main class
String str1 = "testabc.test"; // Input string to be checked
// Display the given string and check if 'abc' appears before a period using abcBeforePeriod method
System.out.println("The given string is: " + str1);
System.out.println("Does 'abc' appear before a period? " + m.abcBeforePeriod(str1));
}
}
Sample Output:
The given strings is: testabc.test Is 'abc' appear before period? true The given string is: test.abctest Is 'abc' appear before period? false
Flowchart:
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a Java program to return true if a given string contain the string 'pop', but the middle 'o' also may other character.
Next: Write a Java program to check whether a prefix string creates using the first specific characters in a given string, appears somewhere else in the string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/java-exercises/string/java-string-exercise-73.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics