/// <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; }