.NET String.Format方法是否允许将字符串放置在固定长度字符串中的固定位置.
" String Goes Here" " String Goes Here " "String Goes Here "
这是如何使用.NET完成的?
编辑 - 我尝试过Format/PadLeft/PadRight致死.它们不起作用.我不知道为什么.我最终编写了自己的函数来完成这项工作.
编辑 - 我犯了一个错误,并在格式说明符中使用了冒号而不是逗号.应该是"{0,20}".
感谢所有优秀和正确的答案.
Guf*_*ffa 453
这将为您提供您要求的字符串:
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);
Run Code Online (Sandbox Code Playgroud)
Kon*_*lph 64
至少可以使用以下语法来实现第一个和最后一个:
String.Format("{0,20}", "String goes here");
String.Format("{0,-20}", "String goes here");
Run Code Online (Sandbox Code Playgroud)
Spr*_*tty 39
从Visual Studio 2015开始,您也可以使用Interpolated Strings(它是一个编译器技巧),因此您定位的.net框架的版本无关紧要.
string value = "String goes here";
string txt1 = $"{value,20}";
string txt2 = $"{value,-20}";
Run Code Online (Sandbox Code Playgroud)
Joe*_*orn 15
你已经被证明PadLeft和PadRight.这将填补遗失的内容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);
}
}
Run Code Online (Sandbox Code Playgroud)
自我注意:不要忘记更新自己的简历:"有一天,我甚至修复了Joel Coehoorn的代码!" ; -D -Serge
Jed*_*oky 10
试试这个:
"String goes here".PadLeft(20,' ');
"String goes here".PadRight(20,' ');
Run Code Online (Sandbox Code Playgroud)
为中心获取字符串的长度,并使用必要的字符做padleft和padright
int len = "String goes here".Length;
int whites = len /2;
"String goes here".PadRight(len + whites,' ').PadLeft(len + whites,' ');
Run Code Online (Sandbox Code Playgroud)
感谢您的讨论,这个方法也有效(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
Run Code Online (Sandbox Code Playgroud)
这是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);
}
Run Code Online (Sandbox Code Playgroud)
为了帮助理解,使用整数变量firstpad.s.PadLeft(firstpad)应用(正确数量)前导空格.最右边的PadRight(desiredLength)通过应用尾随空格来降低绑定.
| 归档时间: |
|
| 查看次数: |
227236 次 |
| 最近记录: |