所以我有一个扫描仪,它接收一个字符串并将其保存为输入,然后我尝试做
input.replaceAll("?/.,!' ", "");
并打印下面的行进行测试,但它不会替换任何内容
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);
}
}
这是我正在使用的代码。我所需要做的就是一无所有地替换所有标点和空格。
最佳答案
这行:
str.replaceAll(",.?!' ", "");
将搜索整个字符串“,。?!” “ 将被替代。
replaceAll方法的参数是一个正则表达式。
因此,使用类似的方法肯定会更好:
str.replaceAll("[,.?!' ]", "");