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.
/// <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;
}
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);
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).
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}";
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,' ');
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");
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
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
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
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.
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
Source: Stackoverflow.com