Given a string, the task is to check whether a string contains only alphabets or not using ASCII values in JAVA.
Examples:
Input : PrutordotAi
Output : True
Input : Prutor4Prutor
Output : False
Input : null
Output : False
Algorithm:
Get the string
Match the string:
Check if the string is empty or not. If empty, return false
Check if the string is null or not. If null, return false.
If the string is neither empty nor null, then check the string characters one by one for alphabet using ASCII values.
Return true if matched
Pseudocode:
public static boolean isStringOnlyAlphabet(String str)
{
if (str == null || str.equals("")) {
return false;
}
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if ((!(ch >= 'A' && ch <= 'Z'))
&& (!(ch >= 'a' && ch <= 'z'))) {
return false;
}
}
return true;
}
Program: Checking for String containing only Alphabets
// Java program to check if String contains only Alphabets
// using ASCII values
class P_AI {
// Function to check String for only Alphabets
public static boolean isStringOnlyAlphabet(String str)
{
if (str == null || str.equals("")) {
return false;
}
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if ((!(ch >= 'A' && ch <= 'Z'))
&& (!(ch >= 'a' && ch <= 'z'))) {
return false;
}
}
return true;
}
// Main method
public static void main(String[] args)
{
// Checking for True case
System.out.println("Test Case 1:");
String str1 = "PrutordotAi";
System.out.println("Input: " + str1);
System.out.println("Output: " + isStringOnlyAlphabet(str1));
// Checking for String with numeric characters
System.out.println("nTest Case 2:");
String str2 = "Prutor4Prutor";
System.out.println("Input: " + str2);
System.out.println("Output: " + isStringOnlyAlphabet(str2));
// Checking for null String
System.out.println("nTest Case 3:");
String str3 = null;
System.out.println("Input: " + str3);
System.out.println("Output: " + isStringOnlyAlphabet(str3));
// Checking for empty String
System.out.println("nTest Case 4:");
String str4 = "";
System.out.println("Input: " + str4);
System.out.println("Output: " + isStringOnlyAlphabet(str4));
}
}
Output:
Test Case 1:
Input: PrutordotAi
Output: true
Test Case 2:
Input: Prutor4Prutor
Output: false
Test Case 3:
Input: null
Output: false
Test Case 4:
Input:
Output: false