CodeBlanks Logo Icon CodeBlanks

Trim and Pad

C# course · Beginner · Lesson 91/116

Learn formatting with Trim, TrimStart, PadLeft and PadRight.

Trim for edges

The Trim method removes the whitespace characters at the start and end of a string. It is perfect for cleaning stray spaces that often appear in user input. Only the edges are affected; inner spaces are kept.

For example, " hello ".Trim() returns "hello". If you need to clean only one side, use TrimStart or TrimEnd. The original string is still unchanged; the result is a new string.

PadLeft and PadRight

The PadLeft and PadRight methods pad a string with spaces or another character until it reaches a target length. They are commonly used to align columns in a table.

For example, "42".PadLeft(5) returns " 42"; it adds three spaces at the start to reach a total of five characters. You can pass a different character as the second argument: "42".PadLeft(5, '0') gives "00042".

Trimming specific characters

Trim, TrimStart and TrimEnd also accept a parameter: a char[] that lists which characters to remove. This is used to strip punctuation or special signs instead of whitespace.

Example: "***hello***".Trim('*') returns "hello". You can quickly clean marked patterns and get a tidy string without touching the original data.

Exercise Align a table cell

First clean the edges of name with Trim and store it in clean. Then pad it to ten characters with clean.PadRight(10) and print it with Console.WriteLine. End the output with a ! (for example Console.WriteLine(clean + "!")).

Show example solution
Use clean = name.Trim(); to strip spaces, then Console.WriteLine(clean.PadRight(10) + "!"); to print.
Example solution:
using System;

class Program
{
    static void Main()
    {
        string name = "  alex  ";
        string clean = name.Trim();
        Console.WriteLine(clean.PadRight(10) + "!");
    }
}

Test yourself

  1. What is the difference between Trim and TrimEnd?

    string s = "  alex  ";
    Console.WriteLine(s.TrimEnd());
    • Trim cleans both sides, TrimEnd only the end
    • Trim cleans only the start, TrimEnd only the end
    • They do the same thing
    • TrimEnd adds space, Trim removes it
    Show answer

    Trim cleans both sides, TrimEnd only the end — Correct! Trim cleans both sides; TrimEnd only the end.

  2. Pad the number with zeros

    string num = "42";
    string padded = num____;
    Console.WriteLine(padded);
    Show answer
    string num = "42";
    string padded = num.PadLeft(5, '0');
    Console.WriteLine(padded);
  3. Match the call with its result

    " alex ".Trim()
    "alex"
    "42".PadLeft(4, '0')
    "0042"
    "###hi".TrimStart('#')
    "hi"

All lessons in Beginner