Given a string, the task is to write a Java program to check whether the string contains only alphabets or not. If so, then print true, otherwise false.
Examples:
Input: GeeksforGeeks
Output: true
Explanation: The given string contains only alphabets so the output is true.
Input: GeeksforGeeks2020
Output: false
Explanation: The given string contains alphabets and numbers so the output is false.
Input: “”
Output: false
Explanation: The given string is empty so the output is false.
Method 1: This problem can be solved using the ASCII values. Please refer this article for this approach.
Method 2: This problem can be solved using Lambda expression. Please refer this article for this approach.
Method 3: This problem can be solved using Regular Expression. Please refer this article for this approach.
Method 4: This approach uses the methods of Character class in Java
- The idea is to iterate over each character of the string and check whether the specified character is a letter or not using Character.isLetter() method.
- If the character is a letter then continue, else return false.
- If we are able to iterate over the whole string, then return true.
Below is the implementation of the above approach:
Java
class GFG {
public static boolean onlyAlphabets(
String str, int n)
{
if (str == null || str == "" ) {
return false ;
}
for ( int i = 0 ; i < n; i++) {
if (!Character
.isLetter(str.charAt(i))) {
return false ;
}
}
return true ;
}
public static void main(String args[])
{
String str = "GeeksforGeeks" ;
int len = str.length();
System.out.println(
onlyAlphabets(str, len));
}
}
|
Time Complexity: O(N), where N is the size of the given string.
Auxiliary Space: O(1), no extra space required so it is a constant.
Method 5 : Using contains() method and ArrayList
Java
import java.util.*;
import java.lang.*;
class Main{
public static boolean onlyAlphabets(String str, int n)
{
if (str == null || str == "" ) {
return false ;
}
ArrayList<Character> alphabets = new ArrayList<Character>();
String alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ;
for ( int i= 0 ;i<alpha.length();i++)
{
alphabets.add(alpha.charAt(i));
}
for ( int i = 0 ; i < n; i++) {
if (!alphabets.contains(str.charAt(i))) {
return false ;
}
}
return true ;
}
public static void main(String args[])
{
String str = "GeeksforGeeks" ;
int len = str.length();
System.out.println(
onlyAlphabets(str, len));
}
}
|
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
02 Nov, 2022
Like Article
Save Article