Search code examples
javareplaceall

Input1 = input.replaceAll not working


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.


Solution

  • 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("[,.?!' ]", "");