formatting string in MVC /C#

后端 未结 10 1944
不知归路
不知归路 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: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;
        }
    }
    

提交回复
热议问题