In this article, we will learn how to format string as the phone number in C#.
In the example given below, we are passing a string to MaskPhoneNumber() method. MaskPhoneNumber() method returns a string as the formatted phone number. If we didn’t pass anything to MaskPhoneNumber() method it will return ‘Phone number is required !!!‘.
using System; using System.Text.RegularExpressions; namespace Mask_PhoneNumber { class Program { static void Main(string[] args) { Console.WriteLine(MaskPhoneNumber("44575113620")); Console.WriteLine(MaskPhoneNumber("")); Console.WriteLine(MaskPhoneNumber("9876_543210")); Console.WriteLine(MaskPhoneNumber("Test")); Console.WriteLine(MaskPhoneNumber("0987654321")); } public static string MaskPhoneNumber(string value) { try { if (!string.IsNullOrEmpty(value)) { value = Regex.Replace(value, @"\D", ""); // to remove special characters return (double.Parse(value).ToString("(###) ###-####")); } else { return "Phone number is required !!!"; } } catch (Exception) { return "Something went wrong !!!"; } } } }
Output:
As we can see MaskPhoneNumber(“0987654321”) returns (98) 765-4321 where 0 is missing. So, to solve this we have to change code as given below.
using System; using System.Text.RegularExpressions; namespace Mask_PhoneNumber { class Program { static void Main(string[] args) { Console.WriteLine(MaskPhoneNumber("44575113620")); Console.WriteLine(MaskPhoneNumber("")); Console.WriteLine(MaskPhoneNumber("9876_543210")); Console.WriteLine(MaskPhoneNumber("Test")); Console.WriteLine(MaskPhoneNumber("0987654321")); } public static string MaskPhoneNumber(string value) { try { if (!string.IsNullOrEmpty(value)) { value = Regex.Replace(value, @"\D", ""); // to remove the special characters var phoneMask = value.StartsWith("0") ? "(0##) ###-####" : "(###) ###-####"; return (double.Parse(value).ToString(phoneMask)); } else { return "Phone number is required !!!"; } } catch (Exception) { return "Something went wrong !!!"; } } } }
Output:
Please give your valuable feedback and if you have any questions or issues about this article, please let me know.
Also, check How To Create Area In .NET Core