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