如何检查字符串中的所有字符是否全部为字母? [英] How to check if all characters in a String are all letters?

查看:162
本文介绍了如何检查字符串中的所有字符是否全部为字母?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以分隔句子中的单词,但是我不知道如何检查单词是否包含字母以外的其他字符。您不必仅发布一些我可以阅读以帮助我的材料的答案。

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


推荐答案

我要做的是使用 String#matches 并使用正则表达式 [a-zA-Z] +

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






另一种解决方法是 if(Character.isLetter(str.charAt(i))在循环内。

另一个解决方案是这样的

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
}






虽然我更喜欢第一个答案,但使用 String#matches

这篇关于如何检查字符串中的所有字符是否全部为字母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆