I'm trying to write a method that removes all non alphabetic characters from a Java String[]
and then convert the String to an lower case string. I've tried using regular expression to replace the occurence of all non alphabetic characters by ""
.However, the output that I am getting is not able to do so. Here is the code
static String[] inputValidator(String[] line) { for(int i = 0; i < line.length; i++) { line[i].replaceAll("[^a-zA-Z]", ""); line[i].toLowerCase(); } return line; }
However if I try to supply an input that has non alphabets (say -
or .
) the output also consists of them, as they are not removed.
Example Input
A dog is an animal. Animals are not people.
Output that I'm getting
A dog is an animal. Animals are not people.
Output that is expected
a dog is an animal animals are not people
The approach is to use the String. replaceAll method to replace all the non-alphanumeric characters with an empty string.
To remove all non-alphanumeric characters from a string, call the replace() method, passing it a regular expression that matches all non-alphanumeric characters as the first parameter and an empty string as the second. The replace method returns a new string with all matches replaced.
Non-alphanumeric characters can be remove by using preg_replace() function. This function perform regular expression search and replace. The function preg_replace() searches for string specified by pattern and replaces pattern with replacement if found.
You can use a regular expression and replaceAll() method of java. lang. String class to remove all special characters from String.
The problem is your changes are not being stored because Strings are immutable. Each of the method calls is returning a new String
representing the change, with the current String
staying the same. You just need to store the returned String
back into the array.
line[i] = line[i].replaceAll("[^a-zA-Z]", ""); line[i] = line[i].toLowerCase();
Because the each method is returning a String
you can chain your method calls together. This will perform the second method call on the result of the first, allowing you to do both actions in one line.
line[i] = line[i].replaceAll("[^a-zA-Z]", "").toLowerCase();
You need to assign the result of your regex back to lines[i].
for ( int i = 0; i < line.length; i++) { line[i] = line[i].replaceAll("[^a-zA-Z]", "").toLowerCase(); }
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