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

I want to write a static method to which the string is passed, and which checks if the string consists of just letters and spaces. I can use the String length () and charAt (i) methods as needed.

I thought something like the following: (Sorry for 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 that there is probably a mistake in my coding, and there is probably a much simpler way to do this, but please let me know your suggestions!

+4
source share
3 answers

. , , .

^[ A-Za-z]+$

Java , .

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

, ,

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

, ( length() charAt()), .

, - . , "", . , , . true, . "return true" ( , , )

So you change your pseudo code 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;
0
source

Source: https://habr.com/ru/post/1544373/


All Articles