我想编写一个传递字符串的静态方法,并检查该字符串是否仅由字母和空格组成.我可以根据需要使用String的方法length()和charAt(i).
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; } }
解决方法
使用正则表达式.如果它以字母和空格开头,包含和结尾,则仅匹配.
^[ A-Za-z]+$
在Java中,将其初始化为模式并检查它是否与您的字符串匹配.
Pattern p = Pattern.compile("^[ A-Za-z]+$"); Matcher m = p.matcher("aaaaab"); boolean b = m.matches();