If you have any query feel free to chat us!
Happy Coding! Happy Learning!
A pangram is a sentence or a phrase that contains every letter of the alphabet at least once. To check if a given string is a pangram in Java, you can use the following approach:
javaCopy code
public class PangramChecker {
public static boolean isPangram(String str) {
// Convert the input string to lowercase to handle both uppercase and lowercase letters
str = str.toLowerCase();
// Create a boolean array to mark the presence of letters
boolean[] lettersPresent = new boolean[26];
// Iterate through the string and mark the presence of letters in the array
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (Character.isLetter(ch)) {
int index = ch - 'a';
lettersPresent[index] = true;
}
}
// Check if all letters are present in the array
for (boolean isPresent : lettersPresent) {
if (!isPresent) {
return false;
}
}
return true;
}
public static void main(String[] args) {
String sentence1 = "The quick brown fox jumps over the lazy dog";
String sentence2 = "Hello, World!";
System.out.println(isPangram(sentence1)); // Output: true
System.out.println(isPangram(sentence2)); // Output: false
}
}
In this example, we have a method isPangram
that takes a string str
as input and returns true
if it is a pangram and false
otherwise. We convert the input string to lowercase using toLowerCase()
to handle both uppercase and lowercase letters.
We then create a boolean array lettersPresent
of size 26, representing the 26 letters of the English alphabet. We iterate through the string and mark the presence of letters in the array. If the character is a letter, we calculate the index of the letter in the array (0 to 25) by subtracting the ASCII value of 'a' from the character's ASCII value. We set the corresponding element in the lettersPresent
array to true
.
After processing the entire string, we check if all elements in the lettersPresent
array are true
. If any letter is missing, we return false
, indicating that the string is not a pangram. Otherwise, we return true
, indicating that the string is a pangram.
In the main
method, we test the isPangram
method with two sample sentences, and the output shows whether each sentence is a pangram or not.
Comments: 0