Java 检查字符串是否仅是字母 + 空格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24191040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 10:42:31  来源:igfitidea点击:

Checking to see if a string is letters + spaces ONLY?

javaxcodeloopsfor-loopboolean

提问by user3735218

I want to write a static method that is passed a string and that checks to see if the string is made up of just letters and spaces. I can use String's methods length() and charAt(i) as needed..

我想编写一个静态方法,它传递一个字符串并检查字符串是否仅由字母和空格组成。我可以根据需要使用 String 的方法 length() 和 charAt(i) ..

I was thinking something like the following: (Sorry about the pseudocode)

我在想类似以下的事情:(对不起伪代码)

public static boolean onlyLettersSpaces(String s){
for(i=0;i<s.length();i++){
if (s.charAt(i) != a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z) {
return false;
break;
}else {
return true;
}
}

I know there is probably an error in my coding, and there is probably a much easier way to do it, but please let me know your suggestions!

我知道我的编码可能存在错误,并且可能有更简单的方法来做到这一点,但请告诉我您的建议!

采纳答案by Adam Yost

use a regex. This one only matches if it starts with, contains, and ends with only letters and spaces.

使用正则表达式。这个只有在以字母和空格开头、包含和结尾时才匹配。

^[ A-Za-z]+$

In Java, initialize this as a pattern and check if it matches your strings.

在 Java 中,将其初始化为模式并检查它是否与您的字符串匹配。

Pattern p = Pattern.compile("^[ A-Za-z]+$");
Matcher m = p.matcher("aaaaab");
boolean b = m.matches();

回答by Elliott Frisch

That isn't how you test character equality, one easy fix would be

这不是您测试字符相等性的方式,一个简单的解决方法是

public static boolean onlyLettersSpaces(String s){
  for(i=0;i<s.length();i++){
    char ch = s.charAt(i);
    if (Character.isLetter(ch) || ch == ' ') {
      continue;
    }
    return false;
  }
  return true;
}

回答by Durandal

For the constraints your mentioned (use of only length() and charAt()), you got it almost right.

对于您提到的约束(仅使用 length() 和 charAt()),您几乎是正确的。

You do loop over each character and check if its one of the acceptable characters - thats the right way. If you find a non-acceptable character, you immediately return "false", thats also good. Whats wrongis that if you determined to accept the character, you do return true. But the definition says only to return true if allcharacters are accepted. You need to move the "return true" to after the loop (thats the point at which you will know that all characters were accepted)

您确实遍历每个字符并检查它是否是可接受的字符之一 - 这是正确的方法。如果你发现一个不可接受的字符,你立即返回“false”,这也很好。有什么不对的是,如果你决定接受这个角色,你就会返回 true。但是定义只说如果所有字符都被接受,则返回 true 。您需要将“返回真”移动到循环之后(这是您知道所有字符都被接受的点)

So you change your pseudocode to:

因此,您将伪代码更改为:

for (all characters in string) {
    if (character is bad) {
        // one bad character means reject the string, we're done.
        return false;
    }
}
// we now know all chars are good
return true;

回答by Son Truong

Solution:I prefer to use a simple loop.

解决方案:我更喜欢使用简单的循环。

public static boolean isLetterAndSpace(String s) {
    if (s == null || s.length() == 0) {
        return false;
    }

    char[] chars = s.toCharArray();
    for (int index = 0; index < chars.length; index++) {
        int codePoint = Character.codePointAt(chars, index);
        if (!Character.isLetter(codePoint) && !Character.isSpaceChar(codePoint)) {
            return false;
        }
    }

    return true;
}