Home >Java >javaTutorial >How to Efficiently Check if a String Contains Only Letters?

How to Efficiently Check if a String Contains Only Letters?

Barbara Streisand
Barbara StreisandOriginal
2024-11-17 16:05:02374browse

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;
}

Simplicity:

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

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

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!

Statement:
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