Home > Enterprise >  Changing a few char for one the same
Changing a few char for one the same

Time:01-30

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

CodePudding user response:

Ok I find helpful and nice solution.

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

CodePudding user response:

use replaceAll, and reg []

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

CodePudding user response:

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

    }
}
  • Related