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
{"ft_lang_label":"__label__en","ft_lang_prob":0.55530083,"math_prob":0.9827596,"size":6349,"snap":"2021-21-2021-25","text_gpt3_token_len":2019,"char_repetition_ratio":0.13317573,"word_repetition_ratio":0.40338722,"special_character_ratio":0.38447,"punctuation_ratio":0.13959184,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9988251,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-06-21T03:50:54Z\",\"WARC-Record-ID\":\"<urn:uuid:a84472b0-3244-44a7-805f-1e919ee77e1b>\",\"Content-Length\":\"150645\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:bcbcf6e7-60af-442a-8090-4ddc4cc4755e>\",\"WARC-Concurrent-To\":\"<urn:uuid:08e1633f-c4e7-4330-8a2b-36ac99881e6f>\",\"WARC-IP-Address\":\"23.222.12.27\",\"WARC-Target-URI\":\"https://www.geeksforgeeks.org/convert-given-string-to-a-valid-mobile-number/?ref=rp\",\"WARC-Payload-Digest\":\"sha1:LA3IM63YYIOIMEFXDH5A3LLD2QPTOM2U\",\"WARC-Block-Digest\":\"sha1:IUDGQVRAPCOOPWQXLIVQUTC4FY64J74T\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-25/CC-MAIN-2021-25_segments_1623488262046.80_warc_CC-MAIN-20210621025359-20210621055359-00132.warc.gz\"}"}