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.

3
  • you need to put your code inside the for loop Commented Mar 24, 2015 at 15:40
  • possible duplicate of String replace a Backslash Commented Mar 24, 2015 at 15:41
  • Try this instead: str1 = str.replaceAll("[\\p{Punctuation}\\p{Space_Separator}]", ""); Commented Mar 24, 2015 at 15:41

4 Answers 4

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("[,.?!' ]", ""); 
Sign up to request clarification or add additional context in comments.

Comments

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}]", ""); 

Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.