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 u
Here is working method
String name = "Joy.78@,+~'{/>";
String[] stringArray = name.split("\\W+");
StringBuilder result = new StringBuilder();
for (int i = 0; i < stringArray.length; i++) {
result.append(stringArray[i]);
}
String nameNew = result.toString();
nameNew.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();
}
It doesn't work because strings are immutable, you need to set a value e.g.
line[i] = line[i].toLowerCase();
As it already answered , just thought of sharing one more way that was not mentioned here >
str = str.replaceAll("\\P{Alnum}", "").toLowerCase();
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 must reassign the result of toLowerCase()
and replaceAll()
back to line[i]
, since Java String
is immutable (its internal value never changes, and the methods in String
class will return a new String
object instead of modifying the String
object).