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);
}
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.
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.
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.
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]", "");
.
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();
}
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