Bor*_*ens 57 c# formatting string.format padding
我可以使用String.Format()填充任意字符的某个字符串吗?
Console.WriteLine("->{0,18}<-", "hello");
Console.WriteLine("->{0,-18}<-", "hello");
returns
-> hello<-
->hello <-
Run Code Online (Sandbox Code Playgroud)
我现在希望空格是一个任意字符.我不能用padLeft或padRight做的原因是因为我希望能够在不同的地方/时间构造格式字符串,然后实际执行格式化.
--EDIT--
看到我的问题似乎没有现成的解决方案我想出了这个(在编码之前的思考之后)--
EDIT2--
我需要一些更复杂的场景所以我选择了Think Before Coding的第二个建议
[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);
}
Run Code Online (Sandbox Code Playgroud)
因为代码有点太多而无法放入帖子中,所以我将它作为一个要点转移到github:http:
//gist.github.com/533905#file_padded_string_format_info
人们可以很容易地分支它,等等:)
thi*_*ing 30
还有另一种解决方案.
实现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();
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样使用它:
string.Format(StringPadderFormatProvider.Default, "->{0:x20}<-", "Hello");
Run Code Online (Sandbox Code Playgroud)
thi*_*ing 11
您可以将字符串封装在实现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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用这样:
string.Format("->{0:x20}<-", (PaddedString)"Hello");
Run Code Online (Sandbox Code Playgroud)
结果:
"->xxxxxxxxxxxxxxxHello<-"
Run Code Online (Sandbox Code Playgroud)