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

落爺英雄遲暮 提交于 2019-12-11 05:08:31

问题


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

回答1:


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




回答2:


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




回答3:


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).




回答4:


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).




回答5:


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



来源:https://stackoverflow.com/questions/20569685/how-to-check-if-all-characters-in-a-string-are-all-letters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!