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

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

Posted by: admin December 28, 2021 Leave a comment

Questions:

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

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!

Answers:

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.

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

###

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

###

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

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 wrong is that if you determined to accept the character, you do return true. But the definition says only to return true if all characters 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)

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;