相关疑难解决方法(0)

使用任意字符串向左或向右填充string.format(不是padleft或padright)

我可以使用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 …
Run Code Online (Sandbox Code Playgroud)

c# formatting string.format padding

57
推荐指数
2
解决办法
10万
查看次数

标签 统计

c# ×1

formatting ×1

padding ×1

string.format ×1