检查一个字符串是否只有字母+空格? [英] Checking to see if a string is letters + spaces ONLY?

查看:168
本文介绍了检查一个字符串是否只有字母+空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个传递一个字符串的静态方法,并检查字符串是否由字母和空格组成。我可以根据需要使用String的方法length()和charAt(i)。



我正在想下面的东西:(关于伪代码的抱歉)



pre $ public $ {code> public static boolean onlyLettersSpaces(String s){
for(i = 0; i< s.length(); i ++){ (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;




$ b我知道我的编码可能有错误,并可能有一个更简单的方法来做到这一点,但请让我知道你的建议!

解决方案

使用正则表达式。这只能匹配,如果它开始,包含,并以只有字母和空格结束。

  ^ [A-Za-z在Java中,将它初始化为模式,并检查它是否与你的字符串匹配。 




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


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!

解决方案

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();

这篇关于检查一个字符串是否只有字母+空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆