C# 字符串长度一致 空格补齐 可用于记录文本日志

 

 

        /// <summary>
        /// 保证数据长度相同
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="len"></param>
        /// <param name="afterFill">后填充/前填充</param>
        /// <returns></returns>
        public string GetSameLenString(object obj, int len, bool afterFill = true)
        {
            string name = obj.ToString();
            //int count = len - name.Length;//不能用这个 汉字和英文占用的长度不同
            int count = len - System.Text.Encoding.Default.GetBytes(name).Length;

            if (afterFill)
            {
                for (int i = 0; i < count; i++)
                {
                    name += " ";
                }
                return name;

            }
            else
            {
                string value = "";
                for (int i = 0; i < count; i++)
                {
                    value += " ";
                }
                value += name;
                return value;
            }
        }

 

posted @ 2018-12-20 16:40  古兴越  阅读(563)  评论(0编辑  收藏  举报