formatting string in MVC /C#

后端 未结 10 1933
不知归路
不知归路 2021-02-19 03:15

I have a string 731478718861993983 and I want to get this 73-1478-7188-6199-3983 using C#. How can I format it like this ?

Thanks.

相关标签:
10条回答
  • 2021-02-19 03:31

    If the position of "-" is always the same then you can try

    string s = "731478718861993983";
    s = s.Insert(2, "-");
    s = s.Insert(7, "-");
    s = s.Insert(12, "-");
    s = s.Insert(17, "-"); 
    
    0 讨论(0)
  • 2021-02-19 03:31

    Here's how I'd do it; it'll only work if you're storing the numbers as something which isn't a string as they're not able to be used with format strings.

    string numbers = "731478718861993983";
    string formattedNumbers = String.Format("{0:##-####-####-####-####}", long.Parse(numbers));
    

    Edit: amended code, since you said they were held as a string in your your original question

    0 讨论(0)
  • 2021-02-19 03:35

    My first thought is:

    String s = "731478718861993983";
    s = s.Insert(3,"-");
    s = s.Insert(8,"-");
    s = s.Insert(13,"-");
    s = s.Insert(18,"-");
    

    (don't remember if index is zero-based, in which case you should use my values -1) but there is probably some easier way to do this...

    0 讨论(0)
  • 2021-02-19 03:40
    string s = "731478718861993983"
    var newString = (string.Format("{0:##-####-####-####-####}", Convert.ToInt64(s));
    
    0 讨论(0)
  • 2021-02-19 03:43

    If you're dealing strictly with a string, you can make a simple Regex.Replace, to capture each group of 4 digits:

    string str = "731478718861993983";
    str = Regex.Replace(str, "(?!^).{4}", "-$0" ,RegexOptions.RightToLeft);
    Console.WriteLine(str);
    

    Note the use of RegexOptions.RightToLeft, to start capturing from the right (so "12345" will be replaced to 1-2345, and not -12345), and the use of (?!^) to avoid adding a dash in the beginning.
    You may want to capture only digits - a possible pattern then may be @"\B\d{4}".

    0 讨论(0)
  • 2021-02-19 03:44

    If you're dealing with a long number, you can use a NumberFormatInfo to format it:

    First, define your NumberFormatInfo (you may want additional parameters, these are the basic 3):

    NumberFormatInfo format = new NumberFormatInfo();
    format.NumberGroupSeparator = "-";
    format.NumberGroupSizes = new[] { 4 };
    format.NumberDecimalDigits = 0;        
    

    Next, you can use it on your numbers:

    long number = 731478718861993983;
    string formatted = number.ToString("n", format);
    Console.WriteLine(formatted);
    

    After all, .Net has very good globalization support - you're better served using it!

    0 讨论(0)
提交回复
热议问题