Wednesday, November 6, 2013

How to Remove Unwanted Characters From String in Java

Friends, sometimes we may need to remove some unwanted characters from our strings, some thing if we have mobile number for example (123)-456-7891, i want to remove ‘ - and () ‘ symbol before storing this field in the database then ?
Just use this simple code….

Java4s.java

Output

1234567891

Explanation

  • See my string is (123)-456-7891,  so in line number 6, i have written one expression which will removes every thing except these characters  ’a-z, A-Z,0-9
  • Actually replaceAll() is a method in String class, i am passing 2 parameters, 1st parameter is the expression and second is to replace with what ?, in our case am replacing ‘-,),(‘ with nothing, so i have given “”, if want you can pass some characters also try.

No comments:

Post a Comment