how to check if a string contains only alphabets and space in java

how to check if a string contains only alphabets and space in java

To check if a string contains only alphabets and space in Java, you can use the matches method of the String class and pass it a regular expression that matches only alphabets and space.

Here's an example of how you might do this:

re‮‬fer to:lautturi.com
String str = "Hello, World!";

if (str.matches("^[a-zA-Z ]+$")) {
    System.out.println("The string contains only alphabets and space.");
} else {
    System.out.println("The string does not contain only alphabets and space.");
}

In this example, the matches method is used to check if the string str matches the regular expression "^[a-zA-Z ]+$". This regular expression matches any string that consists of only alphabets (uppercase or lowercase) and space.

If the string matches the regular expression, the message "The string contains only alphabets and space." is printed to the console; otherwise, the message "The string does not contain only alphabets and space." is printed.

You can use this approach to check if a string contains only alphabets and space as needed.

Created Time:2017-11-01 12:05:13  Author:lautturi