我能否使用String.Format()来在某个字符串中填充任意字符?
Console.WriteLine("->{0,18}<-", "hello");
Console.WriteLine("->{0,-18}<-", "hello");
returns
-> hello<-
->hello <-
我现在希望空格成为任意字符。 我不能使用padLeft或padRight的原因是,我希望能够在不同的地方/时间构造格式字符串,然后在实际执行格式化时将其应用。
--编辑--
看到似乎没有现成的解决方案,我想出了这个解决方案(在Think Before Coding的建议之后)
--编辑2--
我需要一些更复杂的情况,所以我选择了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);
}
由于代码太长,无法发表在帖子中,我将其作为gist放到了github上:
http://gist.github.com/533905#file_padded_string_format_info
这样人们就能轻松地进行分支等操作 :)