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

时间:2021-04-18 12:08:55
 /// <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?:);
var newStr=new string(paddingChar,(int)num);
if (isLeft)
{
input = newStr + input;
}
else
{
input = input + newStr;
}
return input;
}