先看下麵的這組字元,如果輸出來,它是無法靠右對齊: string[] s1 = { "300", "5", "54210", "6300", "88" }; foreach (string s in s1) { string s2 = s; Console.WriteLine(s2); } C#的處 ...
string[] s1 = { "300", "5", "54210", "6300", "88" }; foreach (string s in s1) { string s2 = s; Console.WriteLine(s2); }Source Code
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