Remove all non alphabetic characters from a String array in java

95,850

Solution 1

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

Solution 2

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();
}

Solution 3

It doesn't work because strings are immutable, you need to set a value e.g.

line[i] = line[i].toLowerCase(); 

Solution 4

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).

Solution 5

As it already answered , just thought of sharing one more way that was not mentioned here >

 str = str.replaceAll("\\P{Alnum}", "").toLowerCase();
Share:
95,850

Related videos on Youtube

hytriutucx
Author by

hytriutucx

Updated on June 07, 2021

Comments

  • hytriutucx
    hytriutucx about 3 years

    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
    
  • DJ.
    DJ. almost 12 years
    Sean, you missed the replaceAll call there.
  • Sean F
    Sean F almost 12 years
    i was going to edit it in but once i submitted and 3 other responses existed saying the same thing i didnt see the point.
  • Lawrence Dol
    Lawrence Dol about 10 years
    Though this is wider than just the latin letters matched by the OPs code; that may or may not be what is needed.

Related