views:

2026

answers:

5

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.

A: 

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");
Konrad Rudolph
I have tried your suggestion. It does not work.
Try again; my code contained a typo at first, I used `:` instead of `,` but I've corrected this now.
Konrad Rudolph
A: 

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,' ');
Jedi Master Spooky
Seems like the String.Format() calls is superfluous.
Joel Coehoorn
Yes I don't knwo why I left it, I am editing now.
Jedi Master Spooky
+1  A: 

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

Atilio Jobson
+3  A: 

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

public static class StringUtils
{
    public 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(padding/2, c).PadRight(padding-(padding/2), c);
    }
}
Joel Coehoorn
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);
shaunmartin
+3  A: 

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

string s = "String goes here";
string line1 = String.Format("{0,27}", s);
string line2 = String.Format("{0,-27}", String.Format("{0," + ((27 + s.Length) / 2).ToString() +  "}", s));
string line3 = String.Format("{0,-27}", s);
Guffa