Normalise a phone number
People type phone numbers however they like. The CRM stores exactly one shape, so the importer either produces that shape or rejects the row.
- Throw away everything that is not a digit.
- A single leading zero is a national prefix and is dropped.
- What is left must be exactly ten digits.
- The country code must itself be one to three digits.
- The result is a plus sign, the country code, then the ten digits. Anything that does not fit gives null.
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.
Where you start
std::optional<std::string> normalisePhone(std::string raw, std::string countryCode) {
}
Worked examples
| Call | Result |
|---|---|
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;
}