.PadLeft()
Published Nov 16, 2024
Contribute to Docs
In C#, the .PadLeft()
method adds padding to the start of a string until it reaches the specified total length. If a padding character is not specified, it defaults to spaces. This method returns a new string, leaving the original string unchanged.
Syntax
string.PadLeft(int totalWidth);
Or, alternatively:
string.PadLeft(int totalWidth, char paddingChar);
totalWidth
: The desired total length of the string after padding.paddingChar
(Optional): The character used for padding. If not specified, a space is used by default.
Example
The following example illustrates the usage of .PadLeft()
in various scenarios:
using System;class Program{static void Main(){string str = "Codecademy"; // Length: 10Console.WriteLine($"String: '{str}'");// Case 1: Padding with default space characterstring paddingDefault = str.PadLeft(15);Console.WriteLine($"Case 1: '{paddingDefault}'");// Case 2: Padding with a specific characterchar paddingChar = '.';string paddingWithChar = str.PadLeft(15, paddingChar);Console.WriteLine($"Case 2: '{paddingWithChar}'");// Case 3: Total width is less than string lengthstring noPadding = str.PadLeft(1);Console.WriteLine($"Case 3: '{noPadding}'");}}
The above example gives the following output:
String: 'Codecademy'Case 1: ' Codecademy'Case 2: '.....Codecademy'Case 3: 'Codecademy'
Codebyte Example
The following runnable example demonstrates different use cases for .PadLeft()
, including padding with spaces by default and padding with a specified character:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C# on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C#
Learn Microsoft's popular C# programming language, used to make websites, mobile apps, video games, VR, and more.Beginner Friendly23 hours