Remove all non alphabetic characters from a String array in java

后端 未结 8 913
难免孤独
难免孤独 2020-12-14 08:11

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

相关标签:
8条回答
  • 2020-12-14 08:30

    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();
    
    0 讨论(0)
  • 2020-12-14 08:41

    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();
    }
    
    0 讨论(0)
  • 2020-12-14 08:41

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

    line[i] = line[i].toLowerCase(); 
    
    0 讨论(0)
  • 2020-12-14 08:41

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

     str = str.replaceAll("\\P{Alnum}", "").toLowerCase();
    
    0 讨论(0)
  • 2020-12-14 08:42

    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();
    
    0 讨论(0)
  • 2020-12-14 08:44

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

    0 讨论(0)
提交回复
热议问题