【问题标题】:How to check if all characters in a String are all letters?如何检查字符串中的所有字符是否都是字母?
【发布时间】:2014-01-01 09:50:01
【问题描述】:

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

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

【问题讨论】:

    标签: java string character


    【解决方案1】:

    我要做的是使用String#matches 并使用正则表达式[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))


    另一种解决方案是这样的

    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

    【讨论】:

    • 看问题是我需要单独检查所有单词,看看它们是否有一个字母以外的字符,以及输出是好词(仅包含字母)还是坏词(例如“Hell0”是一个坏词)
    • 在你的循环中,只需使用if (ss.matches("[a-zA-Z]+")) { // do something }
    • 是的,这非常有效!非常感谢伙计。我很感激。
    【解决方案2】:

    更多参考转到-> How to determine if a String has non-alphanumeric characters?
    对模式“[^a-zA-Z^]”进行以下更改

    【讨论】:

      【解决方案3】:

      不确定我是否理解你的问题,但有

      Character.isAlpha(c);

      您将遍历字符串中的所有字符并检查它们是否是字母(Character 类中还有其他“isXxxxx”方法)。

      【讨论】:

      • 如果我输入“Thanks for help geert3”,它会输出 geert3 is a bad word,因为它包含一个数字。
      【解决方案4】:

      您可以遍历调用Character.isLetter() 的单词中的字符,或者检查它是否与正则表达式匹配,例如[\w]*(只有当它的内容都是字符时才会匹配这个词)。

      【讨论】:

        【解决方案5】:

        您可以使用字符数组来执行此操作。

        char[] a=ss.toCharArray();

        你不能在 perticulor 索引处获得字符。

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-10-09
          • 1970-01-01
          • 2023-04-02
          • 1970-01-01
          • 2013-04-01
          • 1970-01-01
          • 2019-03-28
          • 1970-01-01
          相关资源
          最近更新 更多