ARTICLE

Padding Strings in C#

Posted by Mahesh Chand Articles | String in C# August 21, 2010
This code snippet shows how to pad strings in C#.
Reader Level:

Padding Strings

ThePadLeft and PadRight methods can be used to pad strings. The PadLeft method right-aligns and pads a string so that its rightmost character isthe specified distance from the beginning of the string. The PadRight method left-aligns and pads a string so that its rightmost character is aspecified distance from the end of the string. These methods return newString objects that can either be padded with empty spaces or with custom characters. Listign 3 shows how to use these methods.

Listing 3: Using padding methods

string str1 = "My String";
Console.WriteLine(str1.PadLeft(20, '-'));
string
str2 = "My String";
Console.WriteLine(str2.PadRight(20, '-'));

The output of Listing 3 is shown in Figure 2.

Padd1.gif

Figure 2.



Read C# Strings  to learn more about strings in C#.

Login to add your contents and source code to this article
post comment
     
COMMENT USING
PREMIUM SPONSORS
Over-C is a holistic consortium of communications and technology specialists. We build, deploy and market both business as well as consumer products and solutions.
Get Career Advice from Experts
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Get Career Advice from Experts