Previous Page

Remove unwanted characters from a String - Java short program

Copy and Paste the following code into your favorite Java Integrated Development Environment (IDE) - compile and run.

This short program has the replaceAll function that removes any unwanted characters from a string.

// Description: Removes all special characters and numbers from the user's input

public class removeSpecialCharactersFromString
	public static void main(String[] args)
		String sentence = "Welcome to! Call us at 555-1212 %%//???@home";
		 sentence = sentence.replaceAll("[^a-zA-Z]+"," ");// removes all special characters
							                              // and numbers from the user's input.
												          // After the comma is what gets placed
														  // in between the words.
                                                          // You can even remove white spaces...
                                                          // Just make sure there is no space between
                                                          // the double quotes after the comma.
                                                          // NOTE: inside the bracket are the only characters
                                                          //	   kept in the string.