Pages

Tuesday, 10 September 2013

How to Remove Unwanted Characters From String in Java



riends, 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
1
2
3
4
5
6
7
8
9
10
public class Java4s
{
  public static void main(String[] args)
  {
    String s = "(123)-456-7891";
    s = s.replaceAll("[^a-zA-Z0-9]", "");
    System.out.println(s);
  }

}
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