Home > Java > javaTutorial > body text

How to Efficiently Check if a String Contains Only Letters?

Barbara Streisand
Release: 2024-11-17 16:05:02
Original
311 people have browsed it

How to Efficiently Check if a String Contains Only Letters?

How to Verify if a String Contains Only Letters

The objective is to determine whether a given string consists solely of letters, excluding any numerical characters. For instance, "smith23" would be considered invalid in this context.

Speed vs. Simplicity

The choice between prioritizing speed or simplicity depends on the specific application:

Speed:

For optimal performance, consider using a loop-based approach:

public boolean isAlpha(String name) {
    char[] chars = name.toCharArray();

    for (char c : chars) {
        if(!Character.isLetter(c)) {
            return false;
        }
    }

    return true;
}
Copy after login

Simplicity:

For ease of implementation, a one-line RegEx-based method is recommended:

public boolean isAlpha(String name) {
    return name.matches("[a-zA-Z]+");
}
Copy after login

The above is the detailed content of How to Efficiently Check if a String Contains Only Letters?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template