TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# PadRight and PadLeft: String Columns

Use the PadRight and PadLeft methods. PadRight adds spaces to the right of strings.
PadRight, PadLeft. PadRight adds spaces to the right of strings. PadLeft meanwhile adds to the left. These methods make text easier to read.
Padding a string adds whitespace or other characters to the beginning or end. Any character can be used for padding—not just spaces.StringsChar
PadRight. This method can be used to create columns of text that are left-aligned. We add padding (on the right) up to the specified numbers of characters. This creates a column.

Part 1: We invoke the PadRight method on the "cat" string. This expands, or pads, the width of the string to 10 chars.

Part 2: We call PadRight on a different string. Because we used Console.WriteLine, the new string is written on a separate line.

Console

Tip: Padding strings is most useful for console programs, debug output, or certain text formats.

C# program that uses PadRight using System; class Program { static void Main() { // Part 1: pad a string to 10 chars, and use Console methods to write it. string cat = "cat".PadRight(10); Console.Write(cat); Console.WriteLine("feline"); // Part 2: repeat the same steps. string dog = "poodle".PadRight(10); Console.Write(dog); Console.WriteLine("canine"); } } Output cat feline poodle canine
Example 2. This next example is similar to the first one, but it uses a foreach-loop to build up a columnar, preformatted layout. It shows how to call PadRight on string literals.Foreach

Note: The output of the example will be a simple table with two columns, similar to the previous example.

C# program that uses foreach loop, PadRight using System; class Program { static void Main() { string[] a = new string[] { "cat", "poodle", "lizard", "frog", "photon" }; // Output the header. Console.Write("Key".PadRight(15)); Console.WriteLine("Value"); // Output array. foreach (string s in a) { Console.Write(s.PadRight(15)); Console.WriteLine("noun"); } } } Output Key Value cat noun poodle noun lizard noun frog noun photon noun
Example 3. In many applications, numeric values are aligned to the right. This is how Excel aligns numbers. We see that the numbers on the right are aligned to the right edge.

Note: The same logic can be used to create padding in string data. The console calls are not required.

C# program that uses PadRight and PadLeft using System; class Program { static void Main() { int[] a = new int[] { 1, 40, 6, 700 }; // Output the header. Console.Write("Letter".PadRight(10)); Console.WriteLine("Number".PadLeft(8)); // Output array. foreach (int i in a) { Console.Write("A".PadRight(10)); Console.WriteLine(i.ToString().PadLeft(8)); } } } Output Letter Number A 1 A 40 A 6 A 700
Chars. You can use special characters, such as a dot or dash, for padding. You could use PadRight and PadLeft with periods and connect a string with a right-aligned number.
C# program that uses char for padding using System; class Program { static void Main() { Console.Write("Sam".PadRight(10, '.')); Console.WriteLine("535".PadLeft(4, '.')); Console.Write("Jason".PadRight(10, '.')); Console.WriteLine("1".PadLeft(4, '.')); } } Output Sam........535 Jason........1
PadLeft. Here the PadLeft method is tested with two parameters. The first is the column width in characters and the second is the padding character.

Then: It is then tested with a single parameter—this yields a padding character of a space.

Overload: The padding methods are overloaded. We can call different "forms" of the methods with different arguments.

Decimal places: PadLeft can be used. You can control the number of decimal places with a call like value.ToString("0.00").

C# program that uses PadLeft using System; class Program { static void Main() { string[] words = { "1", "200", "Samuel", "Perls" }; foreach (string word in words) // Loop over words. { // Write ten characters. Console.WriteLine(word.PadLeft(10, '_')); // Write ten characters with space. Console.WriteLine(word.PadLeft(10)); } } } Output _________1 1 _______200 200 ____Samuel Samuel _____Perls Perls
Format string. We can avoid PadRight and PadLeft completely and instead use a format string. This can combine padding methods with other string operations.

Format: We use a comma, and then a negative or positive integer for padding. Positive means right padding, and negative means left padding.

Tip: If we combine multiple string manipulations and concatenations, format strings can be easier to read and shorter.

string.Format
C# program that uses padding format string using System; class Program { static void Main() { string[] values = { "bird", "0", "1" }; foreach (string value in values) { // Use an argument to formatting string for padding. // ... Positive means "pad right." // ... Negative (not shown) means "pad left." string padded = string.Format("{0,5}", value); Console.WriteLine(padded); } } } Output bird 0 1
Implementation. How is PadRight implemented in IL? PadRight and PadLeft are implemented in native code that is external to the IL you can inspect. The PadHelper method is internally called.IL
Implementation of PadRight: C# public string PadRight(int totalWidth) { return this.PadHelper(totalWidth, ' ', true); }
Discussion. It is best to use padding for debugging methods. For more user-focused displays, having an HTML table or DataGridView is better. Padding is also useful on text printouts.DataGridView

Web pages: You can insert the padded text into a PRE element (preformatted). This will render in browsers as a text file.

HTML, XML
String literals. These are string objects. We can pad them. String literals like "Word" can have PadRight called on them. Literals with padding can make headers for our text tables.String Literal
Optimization. The PadLeft and PadRight methods call into a PadHelper method. The code is written in a native computer language and is optimized. But it still must create a new string.

And: This means we can improve performance with a cache of the padded strings—in a Dictionary or array.

DictionaryArray

However: Optimizing padding is often a low-value optimization. Using a StringBuilder to write padding might be a better choice.

StringBuilder: This provides no padding methods. But you can write a certain number of spaces into it, creating padding with no allocation.

StringBuilder
A review. We used the PadRight and PadLeft methods. Presentation layers in applications are sometimes complex. And sometimes complexity just gets in the way.
In these situations, we can use padding to decrease complexity. Padding methods are helpful when developing columnar layouts of numeric data, as with decimal places.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf