TheDeveloperBlog.com

Home | Contact Us

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

C# PadRight and PadLeft Align Strings

This C# page covers 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.

Char

PadRight. This example uses the PadRight method to right align strings. The string literals have padding applied on the right side. The end length of the two strings is 10 characters each. This creates a column.

String Literal

Based on:

.NET 4.5

C# program that uses PadRight

using System;

class Program
{
    static void Main()
    {
	string s = "cat".PadRight(10);
	string s2 = "poodle".PadRight(10);

	Console.Write(s);
	Console.WriteLine("feline");
	Console.Write(s2);
	Console.WriteLine("canine");
    }
}

Output
    The left column is padded to 10 characters wide.

cat       feline
poodle    canine

On both strings, the PadRight method is called with the int 10 as the argument. This expands, or pads, the width of the string to 10 characters. Next in the example, we output the strings to the Console.

IntConsole.WriteLine

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

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 and also on strings in an array.

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. Here's the code that outputs this text layout.

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

Discussion. It is best to use padding for debugging output methods. For more user-focused displays, having an HTML table or DataGridView is better. Padding is also be useful on certain text printouts—movie theater receipts or bank statements.

DataGridView

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

String literals. These are string objects. You can pad them. Above, string literals like "Letter" have PadRight called on them. Literals with padding are usually how you would make headers for your text tables.

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. I can't see inside it.

IL

Implementation of PadRight: C#

public string PadRight(int totalWidth)
{
    return this.PadHelper(totalWidth, ' ', true);
}

Chars. You can use special characters, such as a dot or dash, for padding. For example, you could use PadRight and PadLeft with periods and connect a string with a right-aligned number. This program adds padding with periods.

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. 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

Columns. You can position text in more than one column. This is ideal for developing console programs that provide specific numeric data. But for many applications, using more appealing user interfaces, such as Windows Forms, are preferable.

Tip: On websites HTML tables are often preferable to extra whitespace. The allow the text to flow and wrap.

HTML, XML

Optimization. The PadLeft and PadRight methods call into a PadHelper method. This means the code is written in a native computer language and is likely very optimized. But it still must create a new string.

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

DictionaryArrays

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

Summary. We used the PadRight and PadLeft methods. Presentation layers in your applications are sometimes complex, but sometimes complexity just gets in the way. In these situations, we can use padding to decrease complexity.

And: Padding methods are helpful when developing columnar layouts of numeric data, as with decimal places.


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