Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if a string contains only alphabets in Java using Regex
At first, convert the string into character array. Here, name is our string −
char[] ch = name.toCharArray();
Now, loop through and find whether the string contains only alphabets or not. Here, we are checking for not equal to a letter for every character in the string −
for (char c : ch) {
if(!Character.isLetter(c)) {
return false;
}
Following is an example to check if a string contains only alphabets using Regex
Example
public class Main {
public static boolean checkAlphabet(String name) {
char[] ch = name.toCharArray();
for (char c : ch) {
if(!Character.isLetter(c)) {
return false;
}
}
return true;
}
// Main method
public static void main(String[] args) {
String str1 = "Tom1";
System.out.println("String1 = " + str1);
System.out.println("Does String1 contains only alphabets? = " + checkAlphabet(str1));
String str2 = "Tim";
System.out.println("String2 = " + str2);
System.out.println("Does String2 contains only alphabets? = " + checkAlphabet(str2));
}
}
Output
String1 = Tom1 Does String1 contains only alphabets? = false String2 = Tim Does String2 contains only alphabets? = true
Advertisements