Convert given string to a valid mobile number | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void Validate ( string M ) { int len = M . size ( ) ; string temp = " " ; for ( int i = 0 ; i < len ; i ++ ) { if ( isdigit ( M [ i ] ) ) temp += M [ i ] ; } int nwlen = temp . size ( ) ; if ( nwlen != 10 ) { cout << " Invalid STRNEWLINE " ; return ; } string res = " " ; string x = temp . substr ( 0 , 3 ) ; res += " ( " + x + " ) - " ; x = temp . substr ( 3 , 3 ) ; res += " ( " + x + " ) - " ; x = temp . substr ( 6 , 3 ) ; res += " ( " + x + " ) - " ; x = temp . substr ( 9 , 1 ) ; res += " ( " + x + " ) " ; cout << res << " STRNEWLINE " ; } int main ( ) { string M = "91 ▁ 234rt5%34*0 ▁ 3" ; Validate ( M ) ; }