C# 字符串对齐

来源:互联网 发布:suse yast 安装软件 编辑:程序博客网 时间:2024/06/06 03:39

输出的字符串总是对不齐,于是写了个方法,在此记录下来,以备查看。


                /// </summary>
         /// <param name="str">输出字符串</param>        /// <param name="len">字符串占用的字节长度</param>        /// <returns></returns>        public static string ToSameCharLength(string str, int len)        {            len = len + (len % 2);            int singleChar = 0;            int doubleChar = 0;            int byteCount = 0;                    StringBuilder sb = new StringBuilder();            foreach (char c in str.Trim())            {                sb.Append(c);                byteCount = Encoding.Default.GetByteCount(c + "");                if (byteCount == 1)                {                    singleChar++;                }                else if (byteCount == 2)                {                    doubleChar++;                }                if (singleChar + 2 * doubleChar >len)                {                    if (sb.Length>=1)                    {                        sb.Remove(sb.Length - 1, 1);                    }                    sb.Append("*");                    break;                }else if (singleChar + 2 * doubleChar==len)                {                    break;                }                           }            str = sb.ToString();                         singleChar = 0;            doubleChar = 0;            foreach (char c in str)            {                byteCount = Encoding.Default.GetByteCount(c + "");                if (byteCount == 1)                {                    singleChar++;                }                else if (byteCount == 2)                {                    doubleChar++;                }            }            int count = len - singleChar - 2 * doubleChar;            count = count < 0 ? 0 : count;            return str + new string(' ', count);        }


 

得到想要的整齐的输出:

 

0 0