Changing a few char for one the same

54 Views Asked by At

I have question about String class in Java.

I want remove every punctuation marks. To be exact I use replace() method and replace all marks for: "";

But my question is can I do it more smoothly? Becouse now I replace every sign separately

String line1 = line.replace(".", "");
String line2 = line1.replace("?", "");
String line3 = line2.replace("!", "");
String line4 = line3.replace("\n", "");
4

There are 4 best solutions below

1
Ma Ti On

Ok I find helpful and nice solution.

String line11 = line.replaceAll("[\\p{Punct}]", "");
0
alalalala On

use replaceAll, and reg []

String str = "hellol,lol/,=o/l.o?ll\no,llol";
str = str.replaceAll("[,=/\\n\\?\\.]", "");
System.out.println(str);
0
Kavya Sree On

If we want to replace every punctuation mark then we can use the replaceAll() method in java to achieve that. replaceAll("[^a-zA-Z ]", "")), This line makes a java compiler to understand every character other than alphabets(both lowercase and uppercase) to be replaced by "" i.e,empty. with this we can replace every punctuation marks in a particular string.

public class HelloWorld {
    public static void main(String[] args) {
        String line="Th@#is i*s a Ex()ample St!@ing!@";
        System.out.println(line.replaceAll("[^a-zA-Z ]", ""));

    }
}
0
Reilas On

String.replace is a builder method, so you can chain those calls.

String line1 = line.replace(".", "").replace("?", "").replace("!", "").replace("\n", "");

Although, using the String.replaceAll method is a better approach, if you know regular-expressions.

String line1 = line.replaceAll(Pattern.quote(".?!") + "\\n", "");