. net String。格式方法允许将字符串放置在固定长度的字符串中的固定位置。

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

使用.NET是如何做到这一点的?

编辑-我已经尝试格式/左/右PadRight死亡。它们不起作用。我不知道为什么。最后我写了自己的函数来做这个。

编辑-我犯了一个错误,在格式说明符中使用了冒号而不是逗号。应该是“{0,20}”。

感谢所有精彩而正确的回答。


至少,第一个和最后一个可以使用以下语法:

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

试试这个:

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

对于中心,获取字符串的长度,并使用必要的字符进行左padleft和右padright操作

int len = "String goes here".Length;
int whites = len /2;
"String goes here".PadRight(len + whites,' ').PadLeft(len + whites,' ');

似乎你想要这样的东西,它会把你的字符串放在一个固定长度的字符串中的一个固定点上:

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

注意,如果mystring。Length + leftbuffer超过totallength


你已经学过左键和右键了。这将填补缺失的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);
    }
}

提醒自己:别忘了更新自己的简历:“有一天,我甚至修正了Joel Coehoorn的代码!”, - d哔叽


这将给你你所需要的字符串:

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

这是VB。我创建的NET版本,受到Joel Coehoorn的回答、Oliver的编辑和shaunmartin的评论的启发:

    <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).


我发布了一篇CodeProject文章,可能就是你想要的。

参见:间接宽度和样式格式化的c#方法。

基本上它是一个方法,FormatEx,它的作用类似于String。格式,除了它允许居中对齐修饰符。

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

意味着将varArgs[0]的值置于10个字符宽字段的中心,如果需要额外的填充空间,则向右倾斜。

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

意味着将varArgs[0]的值置于10个字符宽字段的中心,如果需要额外的填充空间,则向左倾斜。

编辑:在内部,它是Joel的PadCenter与一些解析的组合,以重新构造格式和varArgs调用String。格式,做你想要的。

杰西


感谢讨论,这个方法也可以(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

StringCentering() takes two input values and it returns a formatted string. When length of s is greater than or equal to deisredLength, the function returns the original string. When length of s is smaller than desiredLength, it will be padded both ends. 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. The function requires .NET Framework due to PadLeft() and PadRight(). In the last line of the function, binding is from left to right, so firstpad is applied followed by the desiredLength pad.

下面是c#版本:

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

为了帮助理解,这里使用了整数变量firstpad。s.PadLeft(firstpad)应用前导空白(正确数量)。最右边的PadRight(desredlength)通过应用尾随空格来完成较低的绑定。


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

从Visual Studio 2015开始,你也可以使用Interpolated Strings(这是一个编译器的技巧,所以你的目标是哪个版本的。net框架并不重要)。

string value = "String goes here";
string txt1 = $"{value,20}";
string txt2 = $"{value,-20}";