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

标签 c# formatting padding string.format

我可以使用 String.Format() 用任意字符填充某个字符串吗?

Console.WriteLine("->{0,18}<-", "hello");
Console.WriteLine("->{0,-18}<-", "hello");

returns 

->             hello<-
->hello             <-

我现在希望空格是任意字符。 我不能使用 padLeft 或 padRight 的原因是因为我希望能够在不同的位置/时间构造格式字符串,然后实际执行格式化。

--编辑--
看到我的问题似乎没有现成的解决方案,我想出了这个(在 Think Before Coding's suggestion 之后)
--EDIT2--
我需要一些更复杂的场景,所以我选择了 Think Before Coding's second suggestion

[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);
}

因为代码有点多放不上来,我把它移到github上作为要点:
http://gist.github.com/533905#file_padded_string_format_info

人们可以轻松地对其进行分支和任何事情:)

最佳答案

还有另一种解决方案。

实现 IFormatProvider 以返回将传递给 string.Format 的 ICustomFormatter :

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();
}

然后你可以这样使用它:

string.Format(StringPadderFormatProvider.Default, "->{0:x20}<-", "Hello");

关于c# - 使用任意字符串向左或向右填充 string.format(不是 padleft 或 padright),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/541098/

相关文章:

css - CSS 和 Internet Explorer 7 的神秘问题

c# - 使用 C# 和 Objective-C 的 SIP 调用

c# - 随机化 3 种颜色

css - 默认情况下 HTML/CSS 不可见边距,但在使用位置 :absolute 时不可见

HTML/CSS 居中格式

javascript - 变量数据错误

encryption - 如果数据是流式传输或对于 HMAC 来说太大,如何防止 "padding oracle"攻击?

css - 使用显示 : grid and scroll 时没有底部填充

c# - 在 C# 记录中缓存昂贵的重新计算属性或字段

c# - 如何判断列表框中的内容在哪一行