drewwyatt
drewwyatt

Reputation: 6027

How can I use placeholders for characters in a string?

I am trying to use the solution provided in this answer, and have also referenced this article.

Basically, I am trying to format a social security number. This is the method used in the articles linked above:

String.Format(“{0:###-##-####}”, 123456789);

This works great when the number is passed in as shown above, but the number I need to format is contained in a string - so I am essentially doing this (which doesn't work):

String.Format(“{0:###-##-####}”, "123456789");

What is a good way to get around my problem?

Upvotes: 0

Views: 2663

Answers (4)

Ulugbek Umirov
Ulugbek Umirov

Reputation: 12807

You can use Regex.Replace method

string formatted = Regex.Replace("123456789", @"(.{3})(.{2})(.{4})", "$1-$2-$3");

Given you have not so many digits (or letters), you can use multiple dots.

string formatted = Regex.Replace("123456789", @"(...)(..)(....)", "$1-$2-$3");

Upvotes: 1

Win
Win

Reputation: 62290

SSN are normally stored in varchar. If so, you can use like this utility method.

public static string FormatSSN(string ssn)
{
    if (String.IsNullOrEmpty(ssn))
        return string.Empty;

    if (ssn.Length != 9)
        return ssn;

    string first3 = ssn.Substring(0, 3);
    string middle2 = ssn.Substring(6, 2);
    string last4 = ssn.Substring(5, 4);

    return string.Format("{0}-{1}-{2}", first3, middle2, last4);
}

Upvotes: 0

lavrik
lavrik

Reputation: 1474

You can try to print single character

 string.Format("{0}{1}{2}", "123".ToCharArray().Cast<object>().ToArray()) 

Modify this code to support variable length of SSN (if it's necessary - build format string in runtime).

Upvotes: 0

Habib
Habib

Reputation: 223282

You can parse the string to numeric type and then use string.Format like:

String.Format("{0:###-##-####}", long.Parse("123456789"));

You can also use long.TryParse or int.TryParse based on your number, and then use that value in string.Format.

long number;
string str = "123456789";
if (!long.TryParse(str, out number))
{
    //invalid number
}

string formattedStr = String.Format("{0:###-##-####}", number);

Upvotes: 3

Related Questions