Convert given string to a valid mobile number | Java program for the above approach ; Function to print the valid and formatted phone number ; Length of given String ; Store digits in temp ; Iterate given M ; If any digit , append it to temp ; Find new length of String ; If length is not equal to 10 ; Store final result ; Make groups of 3 digits and enclose them within ( ) and separate them with " - " 0 to 2 index 1 st group ; 3 to 5 index 2 nd group ; 6 to 8 index 3 rd group ; 9 to 9 index last group ; Print final result ; Driver Code ; Given String ; Function Call
import java . util . * ; class GFG { static void Validate ( String M ) { int len = M . length ( ) ; String temp = " " ; for ( int i = 0 ; i < len ; i ++ ) { if ( Character . isDigit ( M . charAt ( i ) ) ) temp += M . charAt ( i ) ; } int nwlen = temp . length ( ) ; if ( nwlen != 10 ) { System . out . print ( "InvalidNEW_LINE"); return ; } String res = " " ; String x = temp . substring ( 0 , 3 ) ; res += " ( " + x + " ) - " ; x = temp . substring ( 3 , 6 ) ; res += " ( " + x + " ) - " ; x = temp . substring ( 6 , 9 ) ; res += " ( " + x + " ) - " ; x = temp . substring ( 9 , 10 ) ; res += " ( " + x + " ) " ; System . out . print ( res + "NEW_LINE"); } public static void main ( String [ ] args ) { String M = "91 ▁ 234rt5%34*0 ▁ 3" ; Validate ( M ) ; } }