Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string contains only alphabets

Tags:

java

string

I'm new to Java programming and I need help. Create a table of String and the user gives the size. Subsequently, the user gives String. I want to print the characters but without the characters which are not letters of the alphabet (eg. 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;
    }


}

I am looking on the internet for this code:

    if (str.matches("[a-zA-Z]")){
System.out.println(str);
}
like image 685
Mary Avatar asked Nov 02 '12 19:11

Mary


People also ask

How do I check if a string contains only alphabets?

Regex can be used to check a string for alphabets. String. matches() method is used to check whether or not the string matches the given regex.

Are strings only alphabets?

Explanation: The given string contains only alphabets so the output is true. Explanation: The given string contains alphabets and numbers so the output is false.

How do I check if a string contains only certain characters?

Use the re. match() method to check if a string contains only certain characters. The re. match method will return a match object if the string only contains the specified characters, otherwise None is returned.


2 Answers

You can do this with a very simple regular expression: s/[^A-z]//g. This will substitute nothing for all characters in the string which aren't in the range A-z, which encapsulates all letters (upper and lowercase). Simply do new_string = old_string.replaceAll("[^A-z]", "");.

like image 54
asthasr Avatar answered Sep 26 '22 01:09

asthasr


Since you're new to programming and don't want to involve in the RegEx world (yet), you can create a method that returns a String with letters only:

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();
}
like image 25
Luiggi Mendoza Avatar answered Sep 24 '22 01:09

Luiggi Mendoza