Format a Social Security Number (SSN) as XXX-XX-XXXX from XXXXXXXXX
I am get开发者_运维问答ting a social security number (SSN) from a data warehouse. While posting it to a CRM I want it to be formatted like XXX-XX-XXXX
instead of XXXXXXXXX
.
It's like converting a simple string with dashes at positions 4
and 7
. I am pretty new to C#, so what is the best way to do this?
For a simple, short, and self commenting solution, try:
String.Format("{0:000-00-0000}", 123456789)
123456789
representing your SSN variable.
Check out the String.Insert method.
string formattedSSN = unformattedSSN.Insert(5, "-").Insert(3, "-");
string ssn = "123456789";
string formattedSSN = string.Join("-",
ssn.Substring(0,3),
ssn.Substring(3,2),
ssn.Substring(5,4));
@George's option is probably cleaner if the SSN is stored as a numeric rather than as a string.
start indexes corrected.
Just in case this helps someone, here is a method I created to mask and format a SSN:
USAGE:
string ssn = "123456789";
string masked = MaskSsn(ssn); // returns xxx-xx-6789
CODE:
public static string MaskSsn(this string ssn, int digitsToShow = 4, char maskCharacter = 'x')
{
if (String.IsNullOrWhiteSpace(ssn)) return String.Empty;
const int ssnLength = 9;
const string separator = "-";
int maskLength = ssnLength - digitsToShow;
// truncate and convert to number
int output = Int32.Parse(ssn.Replace(separator, String.Empty).Substring(maskLength, digitsToShow));
string format = String.Empty;
for (int i = 0; i < maskLength; i++) format += maskCharacter;
for (int i = 0; i < digitsToShow; i++) format += "0";
format = format.Insert(3, separator).Insert(6, separator);
format = "{0:" + format + "}";
return String.Format(format, output);
}
Without data validation and assuming that you only get 9 character string, I would go with something like this -
return s.Substring(0, 3) + "-" + s.Substring(3, 2) + "-" + s.Substring(5, 4);
But...I am also pretty new...so GendoIkari's answer is soo much better.
Above answer might be raise exception when string not fixed length.
In my case I used following way SSN formating and its working.
string SSN = "56245789";
if (SSN.Length > 3 && SSN <= 5)
SSN = SSN.Insert(3, "-");
else if (SSN.Length > 5)
SSN = SSN.Insert(5, "-").Insert(3, "-");
Hence SSN will get 562-45-789.
George Johnston's answer is a great answer and the cleanest. Just needs a bit extra work in case there are one or two leading 0's, and this sample assumes your starting point is an SSN in a String format. Check this out:
var socialInString = "003456789";
var formattedSSN = Convert.ToInt32(socialInString).ToString("###-##-####").PadLeft(11, '0');
精彩评论