先看下面的这组字符,如果输出来,它是无法靠右对齐:
class="code_img_closed" src="/Upload/Images/2017120209/0015B68B3C38AA5B.gif" alt="" />logs_code_hide('bdc79ae1-31ec-4b81-86ca-3735f99d5e57',event)" src="/Upload/Images/2017120209/2B1B950FA3DF188F.gif" alt="" />
string[] s1 = { "300", "5", "54210", "6300", "88" }; foreach (string s in s1) { string s2 = s; Console.WriteLine(s2); }Source Code
C#的处理字符串有一个方法,PadLeft(),
string[] s1 = { "300", "5", "54210", "6300", "88" }; foreach (string s in s1) { string s2 = s.PadLeft(7, ' '); Console.WriteLine(s2); }Source Code
程序上面有一个数字7,给了一个死值。如果数组某一个元素长度大于这个数值时,它输出的结果,是无法对齐。下面Insus.NET为解决这个问题,再添加几行代码,先计算出数组元素中,元素的长度,取最长的长度值。
string[] s1 = { "300", "5", "54210", "6300", "88" }; int len = 0; foreach (string s in s1) { if (len < s.Length) len = s.Length; } foreach (string s in s1) { string s2 = s.PadLeft(len, ' '); Console.WriteLine(s2); }Source Code