Roberto Flores
Roberto Flores

Reputation: 789

How to add characters to a string in C#

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.

Upvotes: 3

Views: 5090

Answers (4)

Bill Tarbell
Bill Tarbell

Reputation: 5234

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, "(");

Upvotes: 5

Francesco Bonizzi
Francesco Bonizzi

Reputation: 5302

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);

Upvotes: 0

NetMage
NetMage

Reputation: 26936

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]}";

Upvotes: 0

Mahedi Sabuj
Mahedi Sabuj

Reputation: 2944

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

Upvotes: 1

Related Questions