3

Problem: I would like add characters to a phone.

So instead of displaying ###-###-####, I would like to display (###) ###-####.

I tried the following:

string x = "Phone_Number";
string y = x.Remove(0,2);//removes the "1-"

From here, I am not sure how I would add "()" around ###

Any help would be appreciated.

2
  • Are you using the Masked edit? is this for Win Forms, Web or WPF? there are controls that do the formatting automagically, so there is no need for this kind of code hanky panky.
    – jimjim
    Commented Jun 22, 2017 at 5:39
  • msdn.microsoft.com/en-us/library/…
    – jimjim
    Commented Jun 22, 2017 at 5:40

4 Answers 4

5

It's worth noting that strings are immutable in C#.. meaning that if you attempt to modify one you'll always be given a new string object.

One route would be to convert to a number (as a sanity check) then format the string

var result = String.Format("{0:(###) ###-####}", double.Parse("8005551234"))

If you'd rather not do the double-conversion then you could do something like this:

var result = String.Format("({0}) {1}-{2}", x.Substring(0 , 3), x.Substring(3, 3), x.Substring(6));

Or, if you already have the hyphen in place and really just want to jam in the parenthesis then you can do something like this:

var result = x.Insert(3, ")").Insert(0, "(");
2
  • substring(0-3) ?
    – NetMage
    Commented Jun 21, 2017 at 22:14
  • typed out the answer quickly .. then came in within 2 minutes later and cleaned up any typos .. that being one of them. Commented Jun 21, 2017 at 22:19
1

To insert string in particular position you can use Insert function.

Here is an example:

string phone = "111-222-8765";
phone = phone.Insert(0, "("); // (111-222-8765
phone = phone.Insert(3, ")"); // (111)-222-8765
0

You can use a regular expression to extract the digit groups (regardless of - or () and then output in your desired format:

var digitGroups = Regex.Matches(x, @"(\d{3})-?(\d{3})-?(\d{4})")[0].Groups.Cast<Group>().Skip(1).Select(g => g.Value).ToArray();

var ans = $"({digitGroups[0]}) {digitGroups[1]}-{digitGroups[2]}";
2
0

I would do something like this:

string FormatPhoneNumber(string phoneNumber)
{
    if (string.IsNullOrEmpty(phoneNumber))
        throw new ArgumentNullException(nameof(phoneNumber));

    var phoneParts = phoneNumber.Split('-');
    if (phoneParts.Length < 3)
        throw new ArgumentException("Something wrong with the input number format", nameof(phoneNumber));

    var firstChar = phoneParts[0].First();
    var lastChar = phoneParts[0].Last();
    if (firstChar == '(' && lastChar == ')')
        return phoneNumber;
    else if (firstChar == '(')
        return $"{phoneParts[0]})-{phoneParts[1]}-{phoneParts[2]}";
    else if (lastChar == ')') 
        return $"({phoneParts[0]}-{phoneParts[1]}-{phoneParts[2]}";

    return $"({phoneParts[0]})-{phoneParts[1]}-{phoneParts[2]}";
}

You would use it like this:

string n = "123-123-1234";
var formattedPhoneNumber = FormatPhoneNumber(n);

Not the answer you're looking for? Browse other questions tagged or ask your own question.