formatting string in MVC /C#

后端 未结 10 1934
不知归路
不知归路 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.

提交回复
热议问题