0

So I have a scanner that takes in a string and saves it to input then I try to do

    input.replaceAll("?/.,!' ", ""); 

and print the line below to test it but it just doesn't replace anything

    import java.util.Scanner;

    public class Test2 {
        public static void main (String[]args){
            Scanner sc = new Scanner (System.in);
            System.out.print("Please enter a sentence: ");
            String str = sc.nextLine();

            int x, strCount = 0;
            String str1;

            str1 = str.replaceAll(",.?!' ", "");

            System.out.println(str1);

            for (x = 0; x < str1.length(); x++)
            {
                strCount++;
            }
            System.out.println("Character Count is: " + strCount);

       }

    }

Here is the code I am working with. all I need is to replace all punctuation and spaces with nothing.

Zoolar
  • 15
  • 4

4 Answers4

2

This line :

str.replaceAll(",.?!' ", "");

will search the entire string ",.?!' " to be replaced. The argument of the replaceAll method is a regex.

So, it will surely be better with something like that :

str.replaceAll("[,.?!' ]", "");
vincent
  • 1,214
  • 12
  • 22
2

The first parameter must be a regular expression, here alternative character classes [ ... ].

String str1 = str.replaceAll("[?/.,!' ]", "");

or more generalized s=whitespace, Punct=punctuation:

String str1 = str.replaceAll("[\\s\\p{Punct}]", "");
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
1

Unless the characters ,.?! appear together in the input String no replacement will be made. You could use a character class to specify a range of characters

str1 = str.replaceAll("[,.?!' ]", "");
Reimeus
  • 158,255
  • 15
  • 216
  • 276
1

replaceAll takes a regular expression as the first argument, so it needs to be formatted as such:

str1 = str.replaceAll("[,.?!' ]", "");

More information: http://www.regular-expressions.info/tutorial.html

Sizik
  • 1,066
  • 5
  • 11