Remove certain characters from string

15,333

Solution 1

You can use:

String str1 = str.replaceAll("[.]", "");

instead of:

String str1 = str.replaceAll(".", "");

As @nachokk said, you may want to read something about regex, since replaceAll first parameter expects for a regex expression.

Edit:

Or just this:

String str1 = s.replaceAll("[,.]", "");

to make it all in one sentence.

Solution 2

You can just use String#replace() instead of replaceAll cause String#replaceAll

Replaces each substring of this string that matches the given regular expression with the given replacement.

So in code with replace is

 str = str.replace(",","");
 str = str.replace(".","");

Or you could use a proper regular expression all in one:

str = str.replaceAll("[.,]", "");
Share:
15,333
f3d0r
Author by

f3d0r

Updated on June 13, 2022

Comments

  • f3d0r
    f3d0r almost 2 years

    I want to create a program that gives the number of characters, words, etc... in a user-inputted string. To get the word count I need to remove all the periods and commas form a string. So far I have this:

    import javax.swing.JOptionPane;
    public class WordUtilities
    {
       public static void main(String args[])
       {
          {
          String s = JOptionPane.showInputDialog("Enter in any text.");
    
          int a = s.length();
          String str = s.replaceAll(",", "");
          String str1 = str.replaceAll(".", "");
          System.out.println("Number of characters: " + a);
          System.out.println(str1);
          }
       }
    }
    

    But in the end I get only this:

    Number of characters: (...)
    

    Why is it not giving me the string without the commas and periods? What do I need to fix?

  • Admin
    Admin over 10 years
    The . still needs to be escaped to "[\.]"
  • Paul Samsotha
    Paul Samsotha over 10 years
    @JeremyMiller, not in a character class
  • Paul Samsotha
    Paul Samsotha over 10 years
    +1 for difference clarification
  • Paul Samsotha
    Paul Samsotha over 10 years
    You should reverse your code because the explanation is for the latter case
  • Admin
    Admin over 10 years
    @peeskillet - I stand corrected. Thanks!
  • nachokk
    nachokk over 10 years
    @peeskillet i don't understand what you mean
  • Paul Samsotha
    Paul Samsotha over 10 years
    The code at the bottom matches your answer description. So put that code first. Then you can use the OR for the relaceAll case. Make more logically sense and will make your answer flow more smoothly
  • Paul Samsotha
    Paul Samsotha over 10 years
    I like your answer the best. People are so used to creating new strings, they forget you can just make the old string equal the modified string, but in which case, you should've used s instead of str