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!
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With