Pad w lewo lub w prawo ze sznurkiem.format (nie padleft lub padright) z dowolnym ciągiem

Czy mogę użyć String.Format () aby wstawić określony ciąg z dowolnymi znakami?

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

returns 

->             hello<-
->hello             <-

Chcę teraz, aby spacje były dowolnymi znakami. Powodem, dla którego nie mogę tego zrobić z padLeft lub padRight jest to, że chcę być w stanie skonstruować ciąg formatowania w innym miejscu/czasie, a następnie formatowanie jest faktycznie wykonywane.

--EDIT--
Widzialem ze nie ma istniejacego rozwiazania mojego problemu wpadlem na to (po mysl Przed sugestią kodowania)
--EDIT2--
Potrzebowałem bardziej skomplikowanych scenariuszy, więc poszedłem na pomyśleć przed drugą sugestią kodowania

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

Ponieważ kod był trochę za dużo, aby umieścić w poście, przeniosłem go do github jako gist:
http://gist.github.com/533905#file_padded_string_format_info

Tam ludzie bez problemu to rozgałęziają i co tam :)

Author: Community, 2009-02-12

4 answers

Jest inne rozwiązanie.

Zaimplementuj IFormatProvider, aby zwrócić ICustomFormatter, które zostaną przekazane do 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();
}

Wtedy możesz użyć go tak:

string.Format(StringPadderFormatProvider.Default, "->{0:x20}<-", "Hello");
 30
Author: thinkbeforecoding,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-26 06:52:55

Można zamknąć łańcuch w strukturze implementującej 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);
   }
}

Następnie użyj tego w ten sposób:

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

Wynik:

"->xxxxxxxxxxxxxxxHello<-"
 11
Author: thinkbeforecoding,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-02-12 13:27:20

Edit: źle zrozumiałem twoje pytanie, myślałem, że pytasz, jak pad ze spacjami.

To, o co prosisz, nie jest możliwe przy użyciu komponentu string.Format wyrównanie; string.Format zawsze pola z białymi spacjami. Zobacz komponent wyrównaniasekcja MSDN: formatowanie kompozytowe.

Według Reflector, jest to kod, który biegnie wewnątrz StringBuilder.AppendFormat(IFormatProvider, string, object[]), który jest wywoływany przez string.Format:

int repeatCount = num6 - str2.Length;
if (!flag && (repeatCount > 0))
{
    this.Append(' ', repeatCount);
}
this.Append(str2);
if (flag && (repeatCount > 0))
{
    this.Append(' ', repeatCount);
}

Jak widzisz, spacje są trudne do zapełnienia białymi spacjami.

 3
Author: configurator,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-02-12 13:33:31

Proste:



    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"


 2
Author: Emax83,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-14 09:12:49