Powered by Blogger.

strip only the numbers from any formatted string of phone number

>> Thursday, April 23, 2020

This is a method which returns a string contains numbers init.The phone numbers may contain in differnt formats Ex: (123) 456-7890
                                 123-456-7890
so we can read these type of characters and returns only the numbers using java method isDigit from Character class.

Below method is to strip the extra characters in the phone number format and returns only the numbers of phone number.


/**
  package com.javabynataraj;

public class StringPhoneNum {
 public static void main(String[] args) {
  
  String phone = "(123) 456-7890";
  
  String phoneNum = stripOnlyNumbers(phone);
  
  System.out.println(phoneNum);
 }
 
 /**
  * Method to strip only the numbers from any formatted string
  * if the incoming string has (123) 456-7890 or 123-456-7890
  * this method returns only the numbers which is 1234567890 
  * 
  * @param dbPhoneNum
  * @return only numbers
  */
 public static String stripOnlyNumbers(String dbPhoneNum){
  String numbersOnly = "";
  for(int i=0;i<dbPhoneNum.length();i++){
   if (Character.isDigit(dbPhoneNum.charAt(i)))
    numbersOnly+=dbPhoneNum.charAt(i);
  }
  return numbersOnly;
 }

}

Output: 1234567890

Related Posts Plugin for WordPress, Blogger...
© javabynataraj.blogspot.com from 2009 - 2022. All rights reserved.