简体   繁体   English

如何在字符串中使用占位符?

[英]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? 解决我的问题的好方法是什么?

You can parse the string to numeric type and then use string.Format like: 您可以将字符串解析为数字类型,然后使用string.Format

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.TryParseint.TryParse ,然后在string.Format中使用该值。

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

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

You can use Regex.Replace method 您可以使用Regex.Replace方法

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

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). 修改此代码以支持SSN的可变长度(如果需要-在运行时生成格式字符串)。

SSN are normally stored in varchar. SSN通常存储在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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM