247

Does the .NET String.Format method allow placement of a string at a fixed position within a fixed length string.

"           String Goes Here"
"     String Goes Here      "
"String Goes Here           "

How is this done using .NET?

Edit - I have tried Format/PadLeft/PadRight to death. They do not work. I don't know why. I ended up writing my own function to do this.

Edit - I made a mistake and used a colon instead of a comma in the format specifier. Should be "{0,20}".

Thanks for all of the excellent and correct answers.

4
  • 54
    I've never had a string formatting question that I couldn't answer by going to this page: blog.stevex.net/index.php/string-formatting-in-csharp
    – jcollum
    Mar 13, 2009 at 18:56
  • @jcollum: I'd love to up-vote your answer but no can do for comments
    – Dinah
    Mar 13, 2009 at 19:00
  • PadLeft works for me check that you are leaving the space in PadLeft(20,'HERE GOES A SPACE') Mar 13, 2009 at 19:04
  • What do mean by "leaving the space in". If you mean - am I "trimming" the string, then no. It still doesn't work.
    – user72491
    Mar 13, 2009 at 19:11

10 Answers 10

557

This will give you exactly the strings that you asked for:

string s = "String goes here";
string lineAlignedRight  = String.Format("{0,27}", s);
string lineAlignedCenter = String.Format("{0,-27}",
    String.Format("{0," + ((27 + s.Length) / 2).ToString() +  "}", s));
string lineAlignedLeft   = String.Format("{0,-27}", s);
10
  • 71
    This should be marked as the correct answer to the question, but it looks like the OP has left stackoverflow.
    – Oliver
    Sep 4, 2013 at 10:15
  • 14
    If you look for the green check vs. the highest up-votes, you don't know how to SO ;) Mar 18, 2016 at 19:23
  • 2
    @DaveJellison Seems like someone needs to write a plugin to fix that, or SO should just make it a configurable user preference. Jan 12, 2017 at 17:47
  • 1
    @WalterStabosz couldn't agree more. Jan 13, 2017 at 15:42
  • 3
    why is this done with , instead of : like in all other formatting usecases?
    – LuckyLikey
    Sep 7, 2017 at 14:22
104

As of Visual Studio 2015 you can also do this with Interpolated Strings (its a compiler trick, so it doesn't matter which version of the .net framework you target).

string value = "String goes here";
string txt1 = $"{value,20}";
string txt2 = $"{value,-20}";
2
  • 18
    its a c# 6 feature.
    – LuckyLikey
    Sep 7, 2017 at 14:25
  • 1
    I've been using C#6 for years and didn't know that one! Upvoted :) May 30, 2019 at 13:40
75

The first and the last, at least, are possible using the following syntax:

String.Format("{0,20}", "String goes here");
String.Format("{0,-20}", "String goes here");
0
20

You've been shown PadLeft and PadRight. This will fill in the missing PadCenter.

public static class StringUtils
{
    public static string PadCenter(this string s, int width, char c)
    {
        if (s == null || width <= s.Length) return s;

        int padding = width - s.Length;
        return s.PadLeft(s.Length + padding / 2, c).PadRight(width, c);
    }
}

Note to self: don't forget to update own CV: "One day, I even fixed Joel Coehoorn's code!" ;-D -Serge

1
  • Joel, good snippet - I'm trying to use it and it doesn't quite center, the way it is. Looks like the return line should be something like (I don't have enough rep to edit...): return s.PadLeft((padding / 2) + s.Length, c).PadRight(width, c); Mar 11, 2010 at 19:18
12

try this:

"String goes here".PadLeft(20,' ');
"String goes here".PadRight(20,' ');

for the center get the length of the string and do padleft and padright with the necessary characters

int len = "String goes here".Length;
int whites = len /2;
"String goes here".PadRight(len + whites,' ').PadLeft(len + whites,' ');
2
  • Seems like the String.Format() calls is superfluous. Mar 13, 2009 at 18:50
  • Pad methods are good since the Format options require lengths to be constants (that is, String.Format("{0,-length}", something) won't compile.
    – Roberto
    Dec 10, 2019 at 2:27
6

Thanks for the discussion, this method also works (VB):

Public Function StringCentering(ByVal s As String, ByVal desiredLength As Integer) As String
    If s.Length >= desiredLength Then Return s
    Dim firstpad As Integer = (s.Length + desiredLength) / 2
    Return s.PadLeft(firstpad).PadRight(desiredLength)
End Function
  1. StringCentering() takes two input values and it returns a formatted string.
  2. When length of s is greater than or equal to deisredLength, the function returns the original string.
  3. When length of s is smaller than desiredLength, it will be padded both ends.
  4. Due to character spacing is integer and there is no half-space, we can have an uneven split of space. In this implementation, the greater split goes to the leading end.
  5. The function requires .NET Framework due to PadLeft() and PadRight().
  6. In the last line of the function, binding is from left to right, so firstpad is applied followed by the desiredLength pad.

Here is the C# version:

public string StringCentering(string s, int desiredLength)
{
    if (s.Length >= desiredLength) return s;
    int firstpad = (s.Length + desiredLength) / 2;
    return s.PadLeft(firstpad).PadRight(desiredLength);
}

To aid understanding, integer variable firstpad is used. s.PadLeft(firstpad) applies the (correct number of) leading white spaces. The right-most PadRight(desiredLength) has a lower binding finishes off by applying trailing white spaces.

2
  • 1
    Welcome to SO, chi. This is yet another example of a GREAT first post and answer. +1
    – Brian
    Sep 19, 2013 at 23:04
  • Thanks Brian, the original question at the top of this post is an excellent starting point. I am inspired by all the posts and answers preceding mine.
    – chi
    Sep 19, 2013 at 23:53
1

Here's a VB.NET version I created, inspired by Joel Coehoorn's answer, Oliver's edit, and shaunmartin's comment:

    <Extension()>
Public Function PadCenter(ByVal [string] As String, ByVal width As Integer, ByVal c As Char) As String

    If [string] Is Nothing Then [string] = String.Empty
    If (width <= [string].Length) Then Return [string]

    Dim padding = width - [string].Length
    Return [string].PadLeft([string].Length + (padding \ 2), c).PadRight(width, c)

End Function

<Extension()>
Public Function PadCenter(ByVal [string] As String, ByVal width As Integer) As String

    If [string] Is Nothing Then [string] = String.Empty
    If (width <= [string].Length) Then Return [string]

    Dim padding = width - [string].Length
    Return [string].PadLeft([string].Length + (padding \ 2)).PadRight(width)

End Function

This is set up as a string extension, inside a Public Module (the way you do Extensions in VB.NET, a bit different than C#). My slight change is that it treats a null string as an empty string, and it pads an empty string with the width value (meets my particular needs). Hopefully this will convert easily to C# for anyone who needs it. If there's a better way to reference the answers, edits, and comments I mentioned above, which inspired my post, please let me know and I'll do it - I'm relatively new to posting, and I couldn't figure out to leave a comment (might not have enough rep yet).

0

I posted a CodeProject article that may be what you want.

See: A C# way for indirect width and style formatting.

Basically it is a method, FormatEx, that acts like String.Format, except it allows a centered alignment modifier.

FormatEx("{0,c10}", value);

Means center the value of varArgs[0] in a 10 character wide field, lean right if an extra padding space is required.

FormatEx("{0,c-10}", value);

Means center the value of varArgs[0] in a 10 character wide field, lean left if an extra padding space is required.

Edit: Internally, it is a combination of Joel's PadCenter with some parsing to restructure the format and varArgs for a call to String.Format that does what you want.

-Jesse

-1

it seems like you want something like this, that will place you string at a fixed point in a string of constant length:

Dim totallength As Integer = 100
Dim leftbuffer as Integer = 5
Dim mystring As String = "string goes here"
Dim Formatted_String as String = mystring.PadLeft(leftbuffer + mystring.Length, "-") + String.Empty.PadRight(totallength - (mystring.Length + leftbuffer), "-")

note that this will have problems if mystring.length + leftbuffer exceeds totallength

-9
/// <summary>
/// Returns a string With count chars Left or Right value
/// </summary>
/// <param name="val"></param>
/// <param name="count"></param>
/// <param name="space"></param>
/// <param name="right"></param>
/// <returns></returns>
 public static string Formating(object val, int count, char space = ' ', bool right = false)
{
    var value = val.ToString();
    for (int i = 0; i < count - value.Length; i++) value = right ? value + space : space + value;
    return value;
}
2
  • 5
    Don't use this code - it generates a lot of unnecessary string allocations. Use the builtin format specifiers and padding methods instead. May 2, 2015 at 20:45
  • 1
    holy.. imagine using this inside a loop :)
    – LuckyLikey
    Sep 7, 2017 at 14:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.