zoukankan      html  css  js  c++  java
  • 中英文字符 对齐

    扩展字符串左右对齐方法

    .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,'*')+" ");
                    Console.Write(padRightEx("中文E", 12,'*') + " ");

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

  • 相关阅读:
    sublime text
    php 实例说明 socket通信机制
    nusaop 关于webService
    vim操作集合
    gitHud设置公钥
    redis在window安装并启动
    百度云api 添加标注
    微信小程序bindTap获取对应值
    Java导出excel表
    linux 常用命令
  • 原文地址:https://www.cnblogs.com/muxueyuan/p/5531282.html
Copyright © 2011-2022 走看看