Check If A String Contains Only Letters In Dart
Code snippet for how to Check If A String Contains Only Letters In Dart with sample and detail explanation
Dart is a powerful language now more popular with the advent of Flutter, a framework utilized for building cross-platform applications. This article will guide you through one of the basic yet essential String related tasks in Dart: verifying if a String contains only letters.
Code snippet for Checking if a String Contains Only Letters
The below code snippet demonstrates how to check if a string is composed of only letters in Dart:
bool isStringOnlyLetters(String str) {
return str.trim().isNotEmpty && str.split('').every((char) => RegExp(r'^[a-zA-Z]+$').hasMatch(char));
}
void main() {
print(isStringOnlyLetters('hello')); // returns: true
print(isStringOnlyLetters('hello2')); // returns: false
}
Code Explanation for Checking if a String Contains Only Letters
Let’s break down each part of the code to understand how it works:
-
Firstly, the function
isStringOnlyLetters
is defined which takes a string parameter. This function will be used to check if all characters of the string are letters. -
Inside the function, the Dart trim() function is used which removes all whitespace at the beginning and at the end of the string.
isNotEmpty
then checks if the trimmed String is not empty. -
The string is then split into a List of individual characters using
split('')
. -
The
every
method is used on the List of characters which takes a function that tests each character. If the function returns true for every character, then theevery
method also returns true. -
Inside the
every
method, a pattern for only lower case and upper case English alphabets is defined usingRegExp(r'^[a-zA-Z]+$')
.hasMatch
is then used on each character to verify if it matches the pattern. If it matches, it returns true. -
The function
isStringOnlyLetters
therefore checks if every character of a string is an English letter and returns true only when all characters are letters. -
In the
main
function, theisStringOnlyLetters
function is called with a couple of different strings and the return value is printed. The return value is true when the string contains only English letters and false if there are any other characters.