I need to replace a String which contains white space and periods. I have tried with the following code:
String customerName = "Mr. Raj Kumar";
customerName = customerName.replaceAll(" ", "");
System.out.println("customerName"+customerName);
customerName = customerName.replaceAll(".", "");
System.out.println("customerName"+customerName);
but this results in:
customerName Mr.RajKumar
And
customerName
I am getting the correct customer name from the first SOP, but from second SOP I am not getting any value.
escape the dot, or else it will match any character. This escaping is necessary, because replaceAll() treats the first paramter as a regular expression.
customerName = customerName.replaceAll("\\.", "");
You can do the whole thing with one statement:
customerName = customerName.replaceAll("[\\s.]", "");
use this in your code just for remove periods
customerName = customerName.replaceAll("[.]","");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With