日期:2014-05-17  浏览次数:21350 次

c#字符串自动补齐空格的问题

//每行最多30个字符,不够30个的用空格补齐(前后补齐对称,居中显示).效果如下:
================================
  ============================
    ========================
      ====================
        ================
          ============
            ========
              ====
               ==
               =



求高手给个好的解决办法。
C#

------解决方案--------------------
引用:
String.PadLeft("",30)

写反了
 string pad = "dada";
            pad = pad.PadLeft(30);
------解决方案--------------------
pad = pad.PadLeft(30); 这个应该能满足要求!
------解决方案--------------------
 string str = "==";
                int num = 30;
                int left = (num - str.Length) / 2;
                str = str.PadLeft(left, ' ').PadRight(num, ' ');

------解决方案--------------------
        public static void Main()
        {
            string[] test = {"hello", "hi", "this is a test"};

            test.ToList().ForEach(str => Console.WriteLine( ConvertStringTo30(str)));

            Console.ReadKey();
        }

        public static string ConvertStringTo30(string src)
        {
            if(src.Length> 30)
                throw new ArgumentOutOfRangeException("String is longer than 30");

            var sb = new StringBuilder();
            sb.Append('=', (30 - src.Length) /