Drill

ProblemsJava › validation

Normalise a phone number

mediumvalidationStringsParsingJava

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?

Java 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

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")(String) null

Hint

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

Reference solution in Java
String normalisePhone(String raw, String countryCode) {
    if (countryCode.length() < 1 || countryCode.length() > 3) return null;
    for (char c : countryCode.toCharArray()) if (c < '0' || c > '9') return null;
    StringBuilder d = new StringBuilder();
    for (char c : raw.toCharArray()) 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 Java