6

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?

f3d0r
  • 541
  • 3
  • 12
  • 27
  • 1
    cause replaceAll exepcts a regex.. and `.` is a special symbol – nachokk Dec 31 '13 at 18:52
  • @nachokk So what syntax do I have to use to remove the special symbols (. and ,)? – f3d0r Dec 31 '13 at 18:53
  • You'll need to remove more than just a period and a comma: colons, semicolons, dashes (as opposed to hyphens), apostrophes, double quotes... it's better to remove everything except what you want to count as a character. –  Dec 31 '13 at 19:00
  • @dasblinkenlight s = str.replaceAll("[.]","") from the other question fixed it. Thanks – f3d0r Dec 31 '13 at 19:02

2 Answers2

11

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.

Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
4

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("[.,]", "");
nachokk
  • 14,363
  • 4
  • 24
  • 53