首页 > 技术文章 > 中英文字符 对齐

muxueyuan 2016-05-26 15:19 原文

扩展字符串左右对齐方法

.Net自带的String.PadRight 方法按照MSDN的说明是:
左对齐此字符串中的字符,在右边用空格或指定的 Unicode 字符填充以达到指定的总长度。
实际使用中却发现问题:对于我们中文用户来说,双字节的汉字和单字节的字符同时处理是不可避免的,这时候此方法是不能实现其所谓的对齐效果的;
为此有了以下这个函数,经过这个函数的处理,不管字符串里面是否是中英混排的,都能正确地得到同样占位长度的字符串。
        private string padRightEx(string str,int totalByteCount)
        {
            Encoding coding = Encoding.GetEncoding("gb2312");
            int dcount = 0;
            foreach (char ch in str.ToCharArray())
            {
                if (coding.GetByteCount(ch.ToString()) == 2)
                    dcount++;
            }
            string w = str.PadRight(totalByteCount - dcount);
            return w;
        }    

此函数采用默认的补空格形式。同样可实现补齐任意需要的字符:    
private string padRightEx(string str,int totalByteCount,char ch)
{
...
            string w = str.PadRight(totalByteCount - dcount,ch);
...
}
String.PadLeft也可照此扩展。

例如: 
                Console.Write(padRightEx("中.", 12,'*')+"\r\n");
                Console.Write(padRightEx("中文E", 12,'*') + "\r\n");

输出: 
"中.*********";
"中文E*******";

推荐阅读