c#中控制字符串的格式可以使用String.Format()方法。在中英文混杂的字符串中,如果要对齐,由于中文字符所占的宽度比西文字符宽,采用字符串.PadLeft()或
PadRight()可以补齐字符长度。但是这种方法没法解决中文字符占位比较宽的问题。以下函数实现了一个自定义的补齐方法:
private static 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; }
完整的代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication4 { class Program { static void Main(string[] args) { string s1 = "中文"; string s2 = "语言学English"; Console.WriteLine("{0}{1}", padRightEx(s1, 20), "hello"); Console.WriteLine("{0}{1}", padRightEx(s2, 20), "hello"); Console.ReadLine(); } private static 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; } } }
运行结果: