C# 中英文混合字符串对齐

        private static string padRightEx(string str, int totalByteCount)
        {
            Encoding coding = Encoding.GetEncoding("UTF-8");
            int dcount = 0;
            foreach (char ch in str.ToCharArray())
            {
                if(coding.GetByteCount(ch.ToString())>1)
                    dcount++;
            }
            string w = str.PadRight(totalByteCount - dcount);
            return w;
        }

这段代码来自

https://www.cnblogs.com/chenjiahong/articles/2705437.html

的改进。

采用UTF-8

coding.GetByteCount(ch.ToString())

算出来可能大于2,所以此处进行了改动。

原理:

认为一个中文占2个单位屏幕长度,一个英文占1个单位屏幕长度。

str.PadRight(int totalWidth)

这个函数的totalWidth参数指的是在str字符串右侧填充完空格之后str总的应当占有的长度。

注意这个总的应当占有的长度是字符数,1个中文为1个字符,一个英文为1个字符,所以假设str包含dcount个中文,b个英文,然后需要在str右侧补充c个空格(空格屏幕宽度是1个单元).

那么str字符串右侧补充c个空格之后:

totalWidth=dcount+b+c;

而str补充c个空格之后,实际占得屏幕宽度(也就是我们希望一个字符串占的屏幕宽度totalByteCount )

totalByteCount =2*dcount+b+c;

因此,计算totalWidth:

totalWidth=totalByteCount -dcount=希望占得屏幕宽度-中文字符个数;

也就是下面这行代码的原因:

string w = str.PadRight(totalByteCount - dcount);

发布了108 篇原创文章 · 获赞 126 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/qq_16587307/article/details/102933665