因为在NET中,string的Length并不区分当前字符串包含的字符为单字节还是双字节字符,这样导致我们在通过字符串的PadLeft和PadRight方法处理一些需要排版显示的字符串时,会使得相关显示参差不齐,所以这里就有了这么一个扩展,让双字节显示占用的两个单字节宽度“吐”出来,下面是具体代码
using System.Text.RegularExpressions; public static class StringExtensions { /// <summary> /// 按单字节字符串向左填充长度 /// </summary> /// <param name="input"></param> /// <param name="length"></param> /// <param name="paddingChar"></param> /// <returns></returns> public static string PadLeftWhileDouble(this string input, int length, char paddingChar = '\0') { var singleLength = GetSingleLength(input); return input.PadLeft(length - singleLength + input.Length, paddingChar); } private static int GetSingleLength(string input) { if (string.IsNullOrEmpty(input)) { throw new ArgumentNullException(); } return Regex.Replace(input, @"[^\x00-\xff]", "aa").Length;//计算得到该字符串对应单字节字符串的长度 } /// <summary> /// 按单字节字符串向右填充长度 /// </summary> /// <param name="input"></param> /// <param name="length"></param> /// <param name="paddingChar"></param> /// <returns></returns> public static string PadRightWhileDouble(this string input, int length, char paddingChar = '\0') { var singleLength = GetSingleLength(input); return input.PadRight(length - singleLength + input.Length, paddingChar); } }测试代码如下
Console.WriteLine("123测试测试".PadRightWhileDouble(25) + "1"); Console.WriteLine("123测试测试".PadRightWhileDouble(25, 'A') + "1"); Console.WriteLine("1231212".PadRightWhileDouble(25) + "1"); Console.WriteLine("1231212".PadRightWhileDouble(25, 'A') + "1"); Console.WriteLine("123测试测试".PadLeftWhileDouble(25) + "1"); Console.WriteLine("123测试测试".PadLeftWhileDouble(25, 'A') + "1"); Console.WriteLine("1231212".PadLeftWhileDouble(25) + "1"); Console.WriteLine("1231212".PadLeftWhileDouble(25, 'A') + "1");测试效果图
String扩展 让你在PadLeft和PadRight时不再受单双字节问题困扰
原文地址:http://blog.csdn.net/starfd/article/details/45895241