String format fixed length in C#
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
class Program { static void Main(string[] args) { //this line create a string variable. string stringValue = "red"; string stringValue2 = "green"; string stringValue3 = "yellow"; string stringValue4 = "crimson"; string stringValue5 = "indianred"; Console.WriteLine("string value: " + stringValue); Console.WriteLine("string value2: " + stringValue2); Console.WriteLine("string value3: " + stringValue3); Console.WriteLine("string value4: " + stringValue4); Console.WriteLine("string value5: " + stringValue5); Console.WriteLine("\nformatted string\n"); //make string fixed length 25 Console.WriteLine(stringValue.PadLeft(25, '-')); Console.WriteLine(stringValue2.PadLeft(25, '-')); Console.WriteLine(stringValue3.PadLeft(25, '-')); Console.WriteLine(stringValue4.PadLeft(25, '-')); Console.WriteLine(stringValue5.PadLeft(25, '-')); //another technique to format string fixed length //String.Format("color = |{0,25}|", stringValue); Console.ReadLine(); } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
string value: red string value2: green string value3: yellow string value4: crimson string value5: indianred formatted string ----------------------red --------------------green -------------------yellow ------------------crimson ----------------indianred |
C# string format padding 0,
C# string format leading spaces,
C# pad string with leading zeros,
C# padleft,
C# string format table,