问题
I am getting 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?
回答1:
Check out the String.Insert method.
string formattedSSN = unformattedSSN.Insert(5, "-").Insert(3, "-");
回答2:
For a simple, short, and self commenting solution, try:
String.Format("{0:000-00-0000}", 123456789)
123456789
representing your SSN variable.
回答3:
string ssn = "123456789";
string formattedSSN = string.Join("-",
ssn.Substring(0,3),
ssn.Substring(4,2),
ssn.Substring(6,4));
@George's option is probably cleaner if the SSN is stored as a numeric rather than as a string.
回答4:
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(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);
}
回答5:
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.
回答6:
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.
来源:https://stackoverflow.com/questions/4128263/format-a-social-security-number-ssn-as-xxx-xx-xxxx-from-xxxxxxxxx