Domanda

È possibile utilizzare String.Format () per riempire una certa stringa con i caratteri arbitrari?

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

returns 

->             hello<-
->hello             <-

Ora voglio gli spazi per essere un carattere arbitrario. Il motivo per cui non posso farlo con PadLeft o PadRight è perché voglio essere in grado di costruire la stringa di formato in un diverso luogo / tempo poi la formattazione viene effettivamente eseguita.

- EDIT -
Visto che non sembra essere una soluzione esistente al mio problema mi si avvicinò con questo (dopo pensare prima di Coding suggerimento )
- EDIT2 -
Avevo bisogno di alcuni scenari più complessi così sono andato per pensare prima di codifica secondo suggerimento

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

Dato che il codice era un po 'troppo per mettere in un post, mi sono trasferita a github come un gist:
http://gist.github.com/533905#file_padded_string_format_info

Ci le persone possono facilmente espandersi e qualunque cosa:)

È stato utile?

Soluzione

C'è un'altra soluzione.

Implementare IFormatProvider per restituire un ICustomFormatter che sarà passato al 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();
}

Quindi è possibile utilizzare in questo modo:

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

Altri suggerimenti

Si potrebbe racchiudere la stringa in una struttura che implementa 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);
   }
}

Quindi utilizzare questo genere:

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

Risultati:

"->xxxxxxxxxxxxxxxHello<-"

Semplice:



    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"


Modifica:. Ho frainteso la tua domanda, ho pensato che si stava chiedendo come pad con spazi

Quello che stai chiedendo non è possibile utilizzare il componente di allineamento string.Format; string.Format pastiglie sempre con spazi bianchi. Vedere la Allineamento dei componenti di MSDN: Composite formattazione .

Secondo Reflector, questo è il codice che viene eseguito all'interno StringBuilder.AppendFormat(IFormatProvider, string, object[]) quale è invocato il string.Format:

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

Come si può vedere, gli spazi sono codificati per essere riempito con spazi bianchi.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top