Skip to content
Related Articles
Convert given string to a valid mobile number
• Last Updated : 17 Jun, 2021

Given a string M consisting of letters, digits and symbols, the task is to convert the string to a valid mobile number by removing all characters except the digits in the following format:

• Form a substring of 3 digits while the length of the remaining string is greater than 3.
• Enclose each substring with brackets “()” and separate them with “-“.

If a valid mobile number cannot be obtained, i.e. if the string does not consist of 10 digits, then print -1. Otherwise, print the string obtained.

Examples:

Input: M = “91 234rt5%34*0 3”
Output: “(912)-(345)-(340)-(3)”
Explanation: After removing all extra characters, M = “9123453403”. Therefore, the final string obtained is “(912)-(345)-(340)-(3)”.

Input: M=”9 9 ry7%64 9 7″
Output: “Invalid”
Explanation: After removing extra characters M=”9976497″. Since the length of the string is not equal to 10, the required output is -1.

Approach: Follow the below steps to solve the problem:

• Initialize a string, say S and append all digits of M in S in the given order.
• Now, if the length of S is not 10, print “Invalid”, and end the program.
• Otherwise, if the length of the string S is 10, make a group of 3 characters and enclose it within the brackets “()” and make separate it with “-“.
• Print final string as S.

Below is the solution for the above problem.

## C++

 `// C++ program for the above approach``#include ``using` `namespace` `std;` `// Function to print the valid``// and formatted phone number``void` `Validate(string M)``{``    ``// Length of given string``    ``int` `len = M.size();` `    ``// Store digits in temp``    ``string temp = ``""``;` `    ``// Iterate given M``    ``for` `(``int` `i = 0; i < len; i++) {``        ``// If any digit, append it to temp``        ``if` `(``isdigit``(M[i]))``            ``temp += M[i];``    ``}` `    ``// Find new length of string``    ``int` `nwlen = temp.size();` `    ``// If length is not equal to 10``    ``if` `(nwlen != 10) {``        ``cout << ``"Invalid\n"``;``        ``return``;``    ``}` `    ``// Store final result``    ``string res = ``""``;` `    ``// Make groups of 3 digits and``    ``// enclose them within () and``    ``// separate them with "-"``    ``// 0 to 2 index 1st group``    ``string x = temp.substr(0, 3);``    ``res += ``"("` `+ x + ``")-"``;` `    ``// 3 to 5 index 2nd group``    ``x = temp.substr(3, 3);``    ``res += ``"("` `+ x + ``")-"``;` `    ``// 6 to 8 index 3rd group``    ``x = temp.substr(6, 3);``    ``res += ``"("` `+ x + ``")-"``;` `    ``// 9 to 9 index last group``    ``x = temp.substr(9, 1);``    ``res += ``"("` `+ x + ``")"``;` `    ``// Print final result``    ``cout << res << ``"\n"``;``}` `// Driver Code``int` `main()``{` `    ``// Given string``    ``string M = ``"91 234rt5%34*0 3"``;` `    ``// Fuction Call``    ``Validate(M);``}` `// contributed by ajaykr00kj`

## Java

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

## Python3

 `# Python3 program for the above approach` `# Function to prthe valid``# and formatted phone number``def` `Validate(M):``    ` `    ``# Length of given``    ``lenn ``=` `len``(M)` `    ``# Store digits in temp``    ``temp ``=` `""` `    ``# Iterate given M``    ``for` `i ``in` `range``(lenn):``        ` `        ``# If any digit:append it to temp``        ``if` `(M[i].isdigit()):``            ``temp ``+``=` `M[i]` `    ``# Find new lenngth of``    ``nwlenn ``=` `len``(temp)` `    ``# If lenngth is not equal to 10``    ``if` `(nwlenn !``=` `10``):``        ``print` `(``"Invalid"``)``        ``return` `    ``# Store final result``    ``res ``=` `""` `    ``# Make groups of 3 digits and``    ``# enclose them within () and``    ``# separate them with "-"``    ``# 0 to 2 index 1st group``    ``x ``=` `temp[``0``:``3``]``    ``res ``+``=` `"("` `+` `x ``+` `")-"` `    ``# 3 to 5 index 2nd group``    ``x ``=` `temp[``3` `: ``3` `+` `3``]``    ``res ``+``=` `"("` `+` `x ``+` `")-"` `    ``# 6 to 8 index 3rd group``    ``x ``=` `temp[``6` `: ``3` `+` `6``]``    ``res ``+``=` `"("` `+` `x ``+` `")-"` `    ``# 9 to 9 index last group``    ``x ``=` `temp[``9` `: ``1` `+` `9``]``    ``res ``+``=` `"("` `+` `x ``+` `")"` `    ``# Print final result``    ``print``(res)` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ` `    ``# Given``    ``M ``=` `"91 234rt5%34*0 3"` `    ``# Function Call``    ``Validate(M)` `# This code is contributed by mohit kumar 29`

## C#

 `// C# program for the above approach``using` `System;` `class` `GFG``{` `  ``// Function to print the valid``  ``// and formatted phone number``  ``static` `void` `Validate(``string` `M)``  ``{` `    ``// Length of given String``    ``int` `len = M.Length;` `    ``// Store digits in temp``    ``string` `temp = ``""``;` `    ``// Iterate given M``    ``for` `(``int` `i = 0; i < len; i++)``    ``{` `      ``// If any digit, append it to temp``      ``if` `(Char.IsDigit(M[i]))``        ``temp += M[i];``    ``}` `    ``// Find new length of String``    ``int` `nwlen = temp.Length;` `    ``// If length is not equal to 10``    ``if` `(nwlen != 10)``    ``{``      ``Console.Write(``"Invalid\n"``);``      ``return``;``    ``}` `    ``// Store final result``    ``string` `res = ``""``;` `    ``// Make groups of 3 digits and``    ``// enclose them within () and``    ``// separate them with "-"``    ``// 0 to 2 index 1st group``    ``string` `x = temp.Substring(0, 3);``    ``res += ``"("` `+ x + ``")-"``;` `    ``// 3 to 5 index 2nd group``    ``x = temp.Substring(3, 3);``    ``res += ``"("` `+ x + ``")-"``;` `    ``// 6 to 8 index 3rd group``    ``x = temp.Substring(6, 3);``    ``res += ``"("` `+ x + ``")-"``;` `    ``// 9 to 9 index last group``    ``x = temp.Substring(9, 1);``    ``res += ``"("` `+ x + ``")"``;` `    ``// Print final result``    ``Console.WriteLine(res);``  ``}` `  ``// Driver Code``  ``public` `static` `void` `Main(``string``[] args)``  ``{` `    ``// Given String``    ``string` `M = ``"91 234rt5%34*0 3"``;` `    ``// Fuction Call``    ``Validate(M);``  ``}``}` `// This code is contributed by AnkThon`
Output:
`(912)-(345)-(340)-(3)`

Time Complexity: O(|M|+|S|)
Auxiliary Space: O(|M|+|S|)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer DSA Live Classes

My Personal Notes arrow_drop_up