Checking to see if a string is letters + spaces ONLY?
24,609
Solution 1
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();
Solution 2
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;
}
Author by
user3735218
Updated on April 11, 2020Comments
-
user3735218 about 4 years
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!
-
user3735218 almost 10 yearsWhat is "ch"?*******************
-
Elliott Frisch almost 10 years@user3735218 Sorry, edited. That was a copy paste error.
char ch = s.charAt(i);
-
user3735218 almost 10 yearsIf I put a return statement inside a loop, will the loop cancel? Hoping it does
-
Durandal almost 10 years@user3735218 Yes it will. Try to solve it in real code, you will see that a return followed by break gives a compiler error, since the return makes it impossible to ever reach the break.
-
Durandal almost 10 yearsCharacter.isLetter() returns true for much more than just A-z. Its probably not what the OP needs (I suspect it to be a homework assignment and that the task is to solve both the character ok/bad decision as well as the string loop logic).