Drill

ProblemsC# › validation

Normalise a phone number

mediumvalidationStringsParsingC#

People type phone numbers however they like. The CRM stores exactly one shape, so the importer either produces that shape or rejects the row.

NormalisePhone(raw: string, countryCode: string) → string?

C# needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

public string NormalisePhone(string raw, string countryCode) {
    
}

Worked examples

CallResult
NormalisePhone("0532 123 45 67", "90")"+905321234567"
NormalisePhone("532-123-4567", "90")"+905321234567"
NormalisePhone("(532) 123 45 67", "1")"+15321234567"
NormalisePhone("123", "90")null

Hint

Clean, then drop the leading zero, then check the length. Three steps in that order.

Reference solution in C#
public string NormalisePhone(string raw, string countryCode) {
    if (countryCode.Length < 1 || countryCode.Length > 3) return null;
    foreach (char c in countryCode) if (c < '0' || c > '9') return null;
    var d = new StringBuilder();
    foreach (char c in raw) if (c >= '0' && c <= '9') d.Append(c);
    string s = d.ToString();
    if (s.StartsWith("0")) s = s.Substring(1);
    return s.Length == 10 ? "+" + countryCode + s : null;
}

The same problem in another language

More validation problems in C#