none
Padding in C# RRS feed

  • Question

  • Does C# has any padding function as PadLeft / PadRight to pad strings or numeric data?
    Friday, December 15, 2006 6:34 PM

Answers

  • Use your handy dandy string.Format function such as


    Console.WriteLine(string.Format("({0,5})", "ABC")); // Left
    Console.WriteLine(string.Format("({0,-5})", "ABC")); // Right

     


    Note I could have just passed that into WriteLine w/o string.format such as

    Console.WriteLine("({0,5})", "ABC"); // Left
    Console.WriteLine("({0,-5})", "ABC"); // Right

    Friday, December 15, 2006 8:42 PM
    Moderator
  • you can also use the PadLeft, PadRight methods of the string object....

    string theString = "abc123";

    string finalString = theString.PadLeft(3, '0');

    Saturday, December 16, 2006 1:14 AM
    Moderator
  • Of course. String class has methods with exactly that name for that purpose. Also you can use string constructor to create a sting with one character repeating defined number of times.
    Friday, December 15, 2006 11:31 PM

All replies

  • Use your handy dandy string.Format function such as


    Console.WriteLine(string.Format("({0,5})", "ABC")); // Left
    Console.WriteLine(string.Format("({0,-5})", "ABC")); // Right

     


    Note I could have just passed that into WriteLine w/o string.format such as

    Console.WriteLine("({0,5})", "ABC"); // Left
    Console.WriteLine("({0,-5})", "ABC"); // Right

    Friday, December 15, 2006 8:42 PM
    Moderator
  • Of course. String class has methods with exactly that name for that purpose. Also you can use string constructor to create a sting with one character repeating defined number of times.
    Friday, December 15, 2006 11:31 PM
  • you can also use the PadLeft, PadRight methods of the string object....

    string theString = "abc123";

    string finalString = theString.PadLeft(3, '0');

    Saturday, December 16, 2006 1:14 AM
    Moderator
  • hey, thats actually NOT going to do what you expect.  if you run the code above your value for theString will be "abc123".  the first parameter of the PadLeft() method is the length that you want to ensure theString to be.  if you start with theString = "a" then running the above code will make sure that the length of theString is 3 with the neglected space being filled with "0" so you will end up with this as the value of theString "00a".  but if thestring is already 3 characters long it wont do any padding.  in most cases you will want the first parameter to be the length you want the final string to be (with the padding).
    for example:
    ("abc123").PadLeft(3, '0');// will be "abc123"
    ("abc123").PadLeft(5, '0');// will be "abc123"
    ("abc123").PadLeft(10, '0');// will be "0000abc123"
    ("abc123").PadLeft(15, '0');// will be "000000000abc123"
    
    
    
    
    
    
    
    

     



    • Proposed as answer by contractorwolf Wednesday, July 20, 2011 1:18 PM
    Wednesday, July 20, 2011 1:16 PM