2012-11-02 120 views
5

我是Java编程新手,需要帮助。 创建一个String表格并且用户给出大小。随后,用户给出String。我想打印字符,但没有它不是英文字母的字符(例如,Java 4! - > Java中,JA /,VA? - > JAVA)字符串只包含字母

public static void main (String[] args) { 

String[] x = new String[size]; 
int size; 
String str= ""; 

BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); 

System.out.print("Give me size: "); 
size = Integer.parseInt(input.readLine()); 


    for(int i=0; i<size; i++){ 
    System.out.print("Give me a String: "); 
    str = input.readLine(); 
    x[i]=str; 
    } 


} 

我找上此代码互联网:

if (str.matches("[a-zA-Z]")){ 
System.out.println(str); 
} 
+0

在这里,你最好知道你应该[接受答案](http://meta.stackexchange.com/a/5235/182862)从你的问题的帖子。 –

回答

3

既然你是新的节目,不希望在正则表达式世界(还)涉及,你可以创建一个返回只包含字母String的方法:既然你是新

public String getStringOfLettersOnly(String s) { 
    //using a StringBuilder instead of concatenate Strings 
    StringBuilder sb = new StringBuilder(); 
    for(int i = 0; i < s.length(); i++) { 
     if (Character.isLetter(s.charAt(i))) { 
      //adding data into the StringBuilder 
      sb.append(s.charAt(i)); 
     } 
    } 
    //return the String contained in the StringBuilder 
    return sb.toString(); 
} 
+0

非常感谢!它的工作:) – Mary

0

您可以检查是否string只有alaphabets用正则表达式。下面 是示例代码

String word = "java"; 
Pattern pattern = Pattern.compiles("[a-zA-Z]+"); 
Matcher matcher = pattern.matcher(word); 
System.out.println(pattern.find()); 

或者你可以使用String.matches(regex)String API 了解REGEX in Java

4

你可以用一个很简单的正则表达式做到这一点:s/[^A-z]//g。这将不会替换字符串中不在范围A-z中的所有字符,它会封装所有字母(大写和小写)。只需做new_string = old_string.replaceAll("[^A-z]", "");

+1

为了响应建议的编辑,删除''new_string''和''old_string''并使用单个变量:包括这两个变量使得意图更清晰,并且通常最好将这样的值视为不可变的,而不是重新分配甚至在生产代码中也可以多次使用相同的变量。 – syrion

相关问题