码迷,mamicode.com
首页 > 其他好文 > 详细

String扩展 让你在PadLeft和PadRight时不再受单双字节问题困扰

时间:2018-03-20 12:45:17      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:ram   param   字节   bool   gpo   int   长度   str   als   

 /// <summary>  
        /// 按单字节字符串向左填充长度  
        /// </summary>  
        /// <param name="input"></param>  
        /// <param name="length"></param>  
        /// <param name="paddingChar"></param>  
        /// <returns></returns>  
        public static string PadLeft2(this string input, int length, char paddingChar = \0)
        {
            return Pad(input, length, paddingChar, true);
        }
        /// <summary>  
        /// 按单字节字符串向右填充长度  
        /// </summary>  
        /// <param name="input">输入字符串</param>  
        /// <param name="length">单字节长度</param>  
        /// <param name="paddingChar">补位字符</param>  
        /// <returns></returns>   
        public static string PadRight2(this string input, int length, char paddingChar = \0)
        {
            return Pad( input,  length, paddingChar, false);
        }

        private static string Pad(string input, int length, char paddingChar,bool isLeft)
        {
            var isDoubleChar = Regex.IsMatch(paddingChar.ToString(), @"[^\x00-\xff]");
            var singleLength = Regex.Replace(input, @"[^\x00-\xff]", "aa").Length;
            var num = (length - singleLength) *1.0/(isDoubleChar?2:1);
            var newStr=new string(paddingChar,(int)num);
            if (isLeft)
            {
                input = newStr + input;
            }
            else
            {
                 input = input + newStr;
            }
            return input;
        }

 

String扩展 让你在PadLeft和PadRight时不再受单双字节问题困扰

标签:ram   param   字节   bool   gpo   int   长度   str   als   

原文地址:https://www.cnblogs.com/simadi/p/8608334.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!