Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 588
user3735218 Avatar asked Jun 12 '14 18:06

user3735218


People also ask

How do you check a string with spaces?

In order to check if a String has only unicode digits or space in Java, we use the isDigit() method and the charAt() method with decision making statements. The isDigit(int codePoint) method determines whether the specific character (Unicode codePoint) is a digit. It returns a boolean value, either true or false.

How do I check if a string is just a letter?

We can use the regex ^[a-zA-Z]*$ to check a string for alphabets. This can be done using the matches() method of the String class, which tells whether the string matches the given regex.


2 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();
like image 121
Adam Yost Avatar answered Sep 30 '22 07:09

Adam Yost


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;
}
like image 40
Elliott Frisch Avatar answered Sep 30 '22 06:09

Elliott Frisch