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

std::optional<std::string> normalisePhone(std::string raw, std::string countryCode) {
    
}

Worked examples

CallResult
normalisePhone(std::string("0532 123 45 67"), std::string("90"))std::optional<std::string>(std::string("+905321234567"))
normalisePhone(std::string("532-123-4567"), std::string("90"))std::optional<std::string>(std::string("+905321234567"))
normalisePhone(std::string("(532) 123 45 67"), std::string("1"))std::optional<std::string>(std::string("+15321234567"))
normalisePhone(std::string("123"), std::string("90"))std::nullopt

Hint

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

Reference solution in C++
std::optional<std::string> normalisePhone(std::string raw, std::string countryCode) {
    if (countryCode.size() < 1 || countryCode.size() > 3) return std::nullopt;
    for (char c : countryCode) if (c < '0' || c > '9') return std::nullopt;
    string d;
    for (char c : raw) if (c >= '0' && c <= '9') d += c;
    if (!d.empty() && d[0] == '0') d = d.substr(1);
    if (d.size() != 10) return std::nullopt;
    return "+" + countryCode + d;
}

The same problem in another language

More validation problems in C++