Pad gauche ou à droite avec string.format (non PadLeft ou PadRight) avec chaîne arbitraire

StackOverflow https://stackoverflow.com/questions/541098

Question

Puis-je utiliser String.Format () pour pad une certaine chaîne de caractères arbitraires?

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

returns 

->             hello<-
->hello             <-

Je veux maintenant les espaces à un caractère arbitraire. La raison pour laquelle je ne peux pas le faire avec PadLeft ou PadRight est parce que je veux être en mesure de construire la chaîne de format dans un lieu / heure différente, alors la mise en forme est réellement exécutée.

- EDIT - Vu qu'il ne semble pas être une solution existante à mon problème, je suis venu avec cette (après Réfléchissez avant de suggestion de codage )
- EDIT2 - Je avais besoin des scénarios plus complexes, donc je suis allé Réfléchissez avant la deuxième suggestion de codage

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

Parce que le code était un peu trop à mettre dans un poste, je me suis déplacé à github comme essentiel:
http://gist.github.com/533905#file_padded_string_format_info

les gens peuvent facilement se ramifier et tout:)

Était-ce utile?

La solution

Il y a une autre solution.

Mettre en œuvre IFormatProvider pour retourner un ICustomFormatter qui sera transmis à 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();
}

Ensuite, vous pouvez l'utiliser comme ceci:

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

Autres conseils

Vous pouvez résumer la chaîne dans une struct qui implémente 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);
   }
}

Ensuite, utilisez ce comme ça:

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

résultat:

"->xxxxxxxxxxxxxxxHello<-"

simple:



    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"


Modifier. J'ai mal compris votre question, je croyais que vous demandiez comment pad avec des espaces

Ce que vous demandez est impossible avec le composant d'alignement de string.Format; string.Format pads toujours avec des espaces blancs. Voir la Alignement des composants de MSDN: Mise en forme composite .

Selon réflecteur, c'est le code qui fonctionne à l'intérieur StringBuilder.AppendFormat(IFormatProvider, string, object[]) qui est appelé par string.Format:

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

Comme vous pouvez le voir, les blancs sont codés en dur à remplir par des espaces.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top