Format a ten-digit phone number
Extract the digits from an input string and format exactly ten digits as (XXX) XXX-XXXX.
Course progress
Problem 75 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
text = "555.123.4567"
Expected output
(555) 123-4567
What is happening?
Extract 5551234567, then divide the digits into groups of 3, 3, and 4 and insert the requested punctuation.
Solution strategy
Build the right mental model
Collect only digit characters, validate the final count, then insert the punctuation at fixed positions.
Core concepts
strings · validation
Complexity
Time O(n), space O(n).
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for format-phone-number
using System;
using System.Text;
class Program
{
static string FormatPhoneNumber(string input)
{
var digits = new StringBuilder();
foreach (char symbol in input)
if (char.IsDigit(symbol)) digits.Append(symbol);
if (digits.Length != 10) throw new ArgumentException("Exactly ten digits are required.");
string value = digits.ToString();
return "(" + value.Substring(0, 3) + ") " +
value.Substring(3, 3) + "-" + value.Substring(6, 4);
}
static void Main()
{
Console.WriteLine(FormatPhoneNumber("555.123.4567"));
}
}Knowledge check
Questions students often ask
What is the main idea behind format a ten-digit phone number?
Collect only digit characters, validate the final count, then insert the punctuation at fixed positions.
What is the time and space complexity of this solution?
Time O(n), space O(n).
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.