.NET 用固定空格格式化字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/644017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 12:20:09  来源:igfitidea点击:

.NET Format a string with fixed spaces

.netstring

提问by user72491

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

.NET String.Format 方法是否允许将字符串放置在固定长度字符串内的固定位置。

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

How is this done using .NET?

这是如何使用 .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.

编辑- 我已经尝试过 Format/PadLeft/PadRight 死了。它们不起作用。我不知道为什么。我最终编写了自己的函数来做到这一点。

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

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

Thanks for all of the excellent and correct answers.

感谢所有优秀和正确的答案。

回答by Guffa

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

回答by Konrad Rudolph

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

回答by Sprotty

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

从 Visual Studio 2015 开始,您还可以使用内插字符串执行此操作(这是一个编译器技巧,因此您针对哪个版本的 .net 框架并不重要)。

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

回答by Joel Coehoorn

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

你已经被展示PadLeftPadRight。这将填补缺失的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

自我提示:不要忘记更新自己的简历:“有一天,我什至修复了 Joel Coehoorn 的代码!” ;-D -塞尔吉

回答by Jedi Master Spooky

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

对于中心获取字符串的长度并使用必要的字符执行 padleft 和 padright

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

回答by chi

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

感谢讨论,这个方法也有效(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 sis greater than or equal to deisredLength, the function returns the original string.
  3. When length of sis 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 firstpadis applied followed by the desiredLengthpad.
  1. StringCentering()接受两个输入值并返回一个格式化的字符串。
  2. s 的长度大于或等于deisredLength 时,函数返回原始字符串。
  3. s 的长度小于requiredLength 时,两端都会被填充。
  4. 由于字符间距是整数并且没有半间距,我们可以有不均匀的间距分割。在这个实现中,更大的分裂进入前端。
  5. 该功能需要.NET框架由于PadLeft()PadRight()
  6. 在该函数的最后一行,结合被从左到右,所以firstpad被施加随后desiredLength垫。

Here is the C# version:

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

To aid understanding, integer variable firstpadis 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.

为了帮助理解,使用整数变量firstpads.PadLeft(firstpad)应用(正确数量的)前导空格。最右边的PadRight(desiredLength)通过应用尾随空白具有较低的绑定结束。

回答by Jeff

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

这是我创建的 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).

这在公共模块中设置为字符串扩展(您在 VB.NET 中执行扩展的方式,与 C# 有点不同)。我的细微变化是它将空字符串视为空字符串,并用宽度值填充空字符串(满足我的特定需求)。希望这对于需要它的任何人来说都可以轻松转换为 C#。如果有更好的方法来引用我上面提到的答案、编辑和评论,它们启发了我的帖子,请告诉我,我会这样做 - 我对发帖比较陌生,我无法弄清楚发表评论(可能还没有足够的代表)。

回答by Jesse Chisholm

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

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

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

请参阅:用于间接宽度和样式格式的 AC# 方式。

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

基本上它是一种方法 FormatEx,其作用类似于 String.Format,但它允许使用居中对齐修饰符。

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.

表示将 varArgs[0] 的值集中在 10 个字符宽的字段中,如果需要额外的填充空间,则向右倾斜。

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.

表示将 varArgs[0] 的值集中在 10 个字符宽的字段中,如果需要额外的填充空间,则向左倾斜。

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.

编辑:在内部,它是乔尔的 PadCenter 与一些解析的组合,以重构格式和 varArgs 以调用 String.Format 来执行您想要的操作。

-Jesse

-杰西

回答by Atilio Jobson

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

请注意,如果 mystring.length + leftbuffer 超过 totallength,则会出现问题

回答by Paulos02

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