C# 使用任意字符串向左或向右填充 string.format(不是 padleft 或 padright)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/541098/
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
Pad left or right with string.format (not padleft or padright) with arbitrary string
提问by Boris Callens
Can I use String.Format() to pad a certain string with arbitrary characters?
我可以使用 String.Format() 用任意字符填充某个字符串吗?
Console.WriteLine("->{0,18}<-", "hello");
Console.WriteLine("->{0,-18}<-", "hello");
returns
-> hello<-
->hello <-
I now want the spaces to be an arbitrary character. The reason I cannot do it with padLeft or padRight is because I want to be able to construct the format string at a different place/time then the formatting is actually executed.
我现在希望空格是任意字符。我不能用 padLeft 或 padRight 做到这一点的原因是因为我希望能够在不同的地点/时间构造格式字符串,然后实际执行格式。
--EDIT--
Seen that there doesn't seem to be an existing solution to my problem I came up with this (after Think Before Coding's suggestion)
--EDIT2--
I needed some more complex scenarios so I went for Think Before Coding's second suggestion
--EDIT--
看到我的问题似乎没有现有的解决方案,我想出了这个(在思考之前编码的建议之后)--
EDIT2--
我需要一些更复杂的场景,所以我选择了思考之前的编码第二个建议
[TestMethod]
public void PaddedStringShouldPadLeft() {
string result = string.Format(new PaddedStringFormatInfo(), "->{0:20:x} {1}<-", "Hello", "World");
string expected = "->xxxxxxxxxxxxxxxHello World<-";
Assert.AreEqual(result, expected);
}
[TestMethod]
public void PaddedStringShouldPadRight()
{
string result = string.Format(new PaddedStringFormatInfo(), "->{0} {1:-20:x}<-", "Hello", "World");
string expected = "->Hello Worldxxxxxxxxxxxxxxx<-";
Assert.AreEqual(result, expected);
}
[TestMethod]
public void ShouldPadLeftThenRight()
{
string result = string.Format(new PaddedStringFormatInfo(), "->{0:10:L} {1:-10:R}<-", "Hello", "World");
string expected = "->LLLLLHello WorldRRRRR<-";
Assert.AreEqual(result, expected);
}
[TestMethod]
public void ShouldFormatRegular()
{
string result = string.Format(new PaddedStringFormatInfo(), "->{0} {1:-10}<-", "Hello", "World");
string expected = string.Format("->{0} {1,-10}<-", "Hello", "World");
Assert.AreEqual(expected, result);
}
Because the code was a bit too much to put in a post, I moved it to github as a gist:
http://gist.github.com/533905#file_padded_string_format_info
因为代码有点多,放不下,我把它移到github上作为gist:http:
//gist.github.com/533905#file_padded_string_format_info
There people can easily branch it and whatever :)
在那里人们可以轻松地分支它等等:)
采纳答案by thinkbeforecoding
There is another solution.
还有另一种解决方案。
Implement IFormatProvider
to return a ICustomFormatter
that will be passed to string.Format :
实现IFormatProvider
返回一个ICustomFormatter
将被传递给 string.Format :
public class StringPadder : ICustomFormatter
{
public string Format(string format, object arg,
IFormatProvider formatProvider)
{
// do padding for string arguments
// use default for others
}
}
public class StringPadderFormatProvider : IFormatProvider
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return new StringPadder();
return null;
}
public static readonly IFormatProvider Default =
new StringPadderFormatProvider();
}
Then you can use it like this :
然后你可以像这样使用它:
string.Format(StringPadderFormatProvider.Default, "->{0:x20}<-", "Hello");
回答by configurator
Edit: I misunderstood your question, I thought you were asking how to pad with spaces.
编辑:我误解了你的问题,我以为你在问如何填充空格。
What you are asking is not possible using the string.Format
alignment component; string.Format
always pads with whitespace. See the Alignment Componentsection of MSDN: Composite Formatting.
使用string.Format
对齐组件无法满足您的要求;string.Format
总是用空格填充。请参阅MSDN: Composite Formatting的对齐组件部分。
According to Reflector, this is the code that runs inside StringBuilder.AppendFormat(IFormatProvider, string, object[])
which is called by string.Format
:
根据 Reflector,这是在内部运行的代码,StringBuilder.AppendFormat(IFormatProvider, string, object[])
它被调用string.Format
:
int repeatCount = num6 - str2.Length;
if (!flag && (repeatCount > 0))
{
this.Append(' ', repeatCount);
}
this.Append(str2);
if (flag && (repeatCount > 0))
{
this.Append(' ', repeatCount);
}
As you can see, blanks are hard coded to be filled with whitespace.
如您所见,空白被硬编码为用空白填充。
回答by thinkbeforecoding
You could encapsulate the string in a struct that implements IFormattable
您可以将字符串封装在实现 IFormattable 的结构中
public struct PaddedString : IFormattable
{
private string value;
public PaddedString(string value) { this.value = value; }
public string ToString(string format, IFormatProvider formatProvider)
{
//... use the format to pad value
}
public static explicit operator PaddedString(string value)
{
return new PaddedString(value);
}
}
Then use this like that :
然后像这样使用:
string.Format("->{0:x20}<-", (PaddedString)"Hello");
result:
结果:
"->xxxxxxxxxxxxxxxHello<-"
回答by Emax83
Simple:
简单的:
dim input as string = "SPQR"
dim format as string =""
dim result as string = ""
'pad left:
format = "{0,-8}"
result = String.Format(format,input)
'result = "SPQR "
'pad right
format = "{0,8}"
result = String.Format(format,input)
'result = " SPQR"