formatting string in MVC /C#

后端 未结 10 1974
不知归路
不知归路 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:44

    LINQ-only one-liner:

    var str = "731478718861993983";
    var result = 
        new string(
            str.ToCharArray().
                Reverse(). // So that it will go over string right-to-left
                Select((c, i) => new { @char = c, group = i / 4}). // Keep group number
                Reverse(). // Restore original order
                GroupBy(t => t.group). // Now do the actual grouping
                Aggregate("", (s, grouping) => "-" + new string(
                    grouping.
                        Select(gr => gr.@char).
                        ToArray())).
                ToArray()).
        Trim('-');
    

    This can handle strings of arbitrary lenghs.

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

    Simple (and naive) extension method :

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("731478718861993983".InsertChar("-", 4));
        }
    }
    
    static class Ext
    {
        public static string InsertChar(this string str, string c, int i)
        {
            for (int j = str.Length - i; j >= 0; j -= i)
            {
                str = str.Insert(j, c);
            }
    
            return str;
        }
    }
    
    0 讨论(0)
  • 2021-02-19 03:51

    By using regex:

        public static string FormatTest1(string num)
        {
            string formatPattern = @"(\d{2})(\d{4})(\d{4})(\d{4})(\d{4})";
            return Regex.Replace(num, formatPattern, "$1-$2-$3-$4-$5");
        }
    
        // test
        string test = FormatTest1("731478718861993983");
        // test result: 73-1478-7188-6199-3983
    
    0 讨论(0)
  • 2021-02-19 03:54
    string myString = 731478718861993983;
    myString.Insert(2,"-");
    myString.Insert(7,"-");
    myString.Insert(13,"-");
    myString.Insert(18,"-");
    
    0 讨论(0)
提交回复
热议问题