Replace special characters in a String using java


package in.javatutorials;

/**
* @author javatutorials
* @since version 1.0
*
* Below class replaces the special characters in a string with empty value
*
*/
public class ReplaceSpecialCharacters {

public static final String REG_EXPR = “[!\”#$%&'()*+-./:;<=>?@\\^_{|}~`,.\\[\\]]*”;

/**
* @param args
*/
public static void main(String[] args){
String str = “a – b +c^d!e+f g . h (Pvt) Ltd.”;
//Create class object and call replace special characters method
ReplaceSpecialCharacters rsc = new ReplaceSpecialCharacters();
String afterReplacing = rsc.replaceSpecialChars(str);
System.out.println(“After replacing special characters : “+afterReplacing);
}

/**
* @param string String
* @return string String
*/
public String replaceSpecialChars(String string){
string = string.replaceAll(REG_EXPR, “”);
while(string.indexOf(” “) != -1){
string = string.replaceAll(” “, ” “);
}

return string;
}

}

4 thoughts on “Replace special characters in a String using java

Leave a Reply to Avoid nested loops using Collection Framework in Java | Java Tutorials Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.