51. Transforming a list of phone numbers

This problem is somewhat similar in some aspects to the previous one. However, instead of selecting phone numbers that start with a specified country code, we must transform each number so that they all start with that country code preceded by a +. There are several cases that must be considered:

  • The phone number starts with a 0. That indicates a number without a country code. To modify the number to include the country code we must replace the 0 with the actual country code, preceded by +.
  • The phone number starts with the country code. In this case, we just prepend + sign to the beginning.
  • The phone number starts with + followed by the country code. In this case, the number is already in the expected format.
  • None of these cases applies, therefore the result is obtained by concatenating the country code preceded by + and the phone number. 
For simplicity, we will ignore the possibility that the number is actually prefixed with another country code. You can take it as a further exercise to modify the implementation so that it can handle phone numbers with a different country prefix. These numbers should be removed from the list.

In all of the preceding cases, it is possible that the number could contain spaces. According to the requirements, these must be removed. The std::remove_if() and isspace() functions are used for this purpose.

The following is an implementation of the described solution:

bool starts_with(std::string_view str, std::string_view prefix)
{
return str.find(prefix) == 0;
}

void normalize_phone_numbers(std::vector<std::string>& numbers,
std::string const & countryCode)
{
std::transform(
std::cbegin(numbers), std::cend(numbers),
std::begin(numbers),
[countryCode](std::string const & number) {
std::string result;
if (number.size() > 0)
{
if (number[0] == '0')
result = "+" + countryCode +
number.substr(1);
else if (starts_with(number, countryCode))
result = "+" + number;
else if (starts_with(number, "+" + countryCode))
result = number;
else
result = "+" + countryCode + number;
}

result.erase(
std::remove_if(std::begin(result), std::end(result),
[](const char ch) {return isspace(ch); }),
std::end(result));

return result;
});
}

The following program normalizes a given list of phone numbers according to the requirement and prints them on the console:

int main()
{
std::vector<std::string> numbers{
"07555 123456",
"07555123456",
"+44 7555 123456",
"44 7555 123456",
"7555 123456"
};

normalize_phone_numbers(numbers, "44");

for (auto const & number : numbers)
{
std::cout << number << std::endl;
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset