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);

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值