258

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
  • 55
    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 Commented Mar 13, 2009 at 18:56
  • @jcollum: I'd love to up-vote your answer but no can do for comments Commented Mar 13, 2009 at 19:00
  • PadLeft works for me check that you are leaving the space in PadLeft(20,'HERE GOES A SPACE') Commented 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. Commented Mar 13, 2009 at 19:11

10 Answers 10

572

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);
Sign up to request clarification or add additional context in comments.

10 Comments

This should be marked as the correct answer to the question, but it looks like the OP has left stackoverflow.
If you look for the green check vs. the highest up-votes, you don't know how to SO ;)
@DaveJellison Seems like someone needs to write a plugin to fix that, or SO should just make it a configurable user preference.
@WalterStabosz couldn't agree more.
why is this done with , instead of : like in all other formatting usecases?
|
116

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}";

3 Comments

its a c# 6 feature.
I've been using C#6 for years and didn't know that one! Upvoted :)
How to use for dynamic width, aka if instead of 20, the width is in a variable? Thanks!
77

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");

Comments

21

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 Comment

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);
14

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,' ');

3 Comments

Seems like the String.Format() calls is superfluous.
Pad methods are good since the Format options require lengths to be constants (that is, String.Format("{0,-length}", something) won't compile.
But you can use: ` int width=10; string fmt = $"{{0,{width}}}"; string.Format(fmt, myVar}; `
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 Comments

Welcome to SO, chi. This is yet another example of a GREAT first post and answer. +1
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.
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).

Comments

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

Comments

-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

Comments

-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 Comments

Don't use this code - it generates a lot of unnecessary string allocations. Use the builtin format specifiers and padding methods instead.
holy.. imagine using this inside a loop :)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.