Trim and pad with custom characters in CSharp

Description

The following code shows how to trim and pad with custom characters.

Example


  //from   w  w  w.jav a  2s. co m
using System;  
  
public class TrimPadDemo {  
  public static void Main() {  
    string str = "test"; 
 
    Console.WriteLine("Original string: " + str); 
     
    // Pad on left with spaces. 
    str = str.PadLeft(10); 
    Console.WriteLine("|" + str + "|"); 
 
    // Pad on right with spaces. 
    str = str.PadRight(20); 
    Console.WriteLine("|" + str + "|"); 
 
    // Trim spaces. 
    str = str.Trim(); 
    Console.WriteLine("|" + str + "|"); 
 
    // Pad on left with #s. 
    str = str.PadLeft(10, '#'); 
    Console.WriteLine("|" + str + "|"); 
 
    // Pad on right with #s. 
    str = str.PadRight(20, '#'); 
    Console.WriteLine("|" + str + "|"); 
 
    // Trim #s. 
    str = str.Trim('#'); 
    Console.WriteLine("|" + str + "|"); 
  } 
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var