Wookie Commander
Wookie Commander

Reputation: 13

How to check if all characters in a String are all letters?

I'm able to separate the words in the sentence but I do not know how to check if a word contains a character other than a letter. You don't have to post an answer just some material I could read to help me.

public static void main(String args [])
{
    String sentance;
    String word;
    int index = 1;

    System.out.println("Enter sentance please");
    sentance = EasyIn.getString();

    String[] words = sentance.split(" ");    

    for ( String ss : words ) 
    {
        System.out.println("Word " + index + " is " + ss);
        index++;
    }            
}   

Upvotes: 1

Views: 11715

Answers (5)

Paul Samsotha
Paul Samsotha

Reputation: 209062

What I would do is use String#matches and use the regex [a-zA-Z]+.

String hello = "Hello!";
String hello1 = "Hello";

System.out.println(hello.matches("[a-zA-Z]+"));  // false
System.out.println(hello1.matches("[a-zA-Z]+")); // true

Another solution is if (Character.isLetter(str.charAt(i)) inside a loop.


Another solution is something like this

String set = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
String word = "Hello!";

boolean notLetterFound;
for (char c : word.toCharArray()){  // loop through string as character array
    if (!set.contains(c)){         // if a character is not found in the set
        notLetterfound = true;    // make notLetterFound true and break the loop
        break;                       
    }
}

if (notLetterFound){    // notLetterFound is true, do something
    // do something
}

I prefer the first answer though, using String#matches

Upvotes: 5

Devendra Lattu
Devendra Lattu

Reputation: 2812

For more reference goto-> How to determine if a String has non-alphanumeric characters?
Make the following changes in pattern "[^a-zA-Z^]"

Upvotes: 1

deepak tiwari
deepak tiwari

Reputation: 107

you can use charector array to do this like..

char[] a=ss.toCharArray();

not you can get the charector at the perticulor index.

with "word "+index+" is "+a[index];

Upvotes: -1

stripybadger
stripybadger

Reputation: 5009

You could loop through the characters in the word calling Character.isLetter(), or maybe check if it matches a regular expression e.g. [\w]* (this would match the word only if its contents are all characters).

Upvotes: 0

geert3
geert3

Reputation: 7341

Not sure if I understand your question, but there is the

Character.isAlpha(c);

You would iterate over all characters in your string and check whether they are alphabetic (there are other "isXxxxx" methods in the Character class).

Upvotes: 0

Related Questions