2010-11-05 8 views
12

Non ho trovato il modo per farlo. Quello che ho trovato era più o meno sulla linea di questo (http://blog.stevex.net/string-formatting-in-csharp/):È possibile definire il numero massimo di caratteri nelle stringhe in formato C# come in C printf?

Non c'è davvero alcuna formattazione all'interno di una stringa, al di là dell'allineamento. L'allineamento funziona per qualsiasi argomento stampato in una chiamata String.Format. esempio genera

String.Format(“->{1,10}<-”, “Hello”); // gives "->     Hello<-" (left padded to 10) 
String.Format(“->{1,-10}<-”, “Hello”); // gives "->Hello     <-" (right padded to 10) 
+0

Che cosa stai cercando di raggiungere? Puoi pubblicare esempi di ciò che vorresti vedere? – Oded

+0

Sto provando a convertire le stringhe in formato C in stringhe in formato C#. in C è possibile specificare% -4.4s e simili. –

+0

perché il voto negativo? questa è una domanda essenziale! –

risposta

7

Quello che vuoi non è "nativamente", sostenuto da stringa di formattazione C#, come i String.ToString metodi dell'oggetto stringa appena restituiscono la stringa stessa.

Quando si chiama

string.Format("{0:xxx}",someobject); 

se someObject implementa l'interfaccia IFormattable, il metodo di overload ToString(string format,IFormatProvider formatProvider) viene chiamato, con "xxx", come format parametro.

Quindi, al massimo, questo non è un difetto nella progettazione della formattazione di stringhe .NET, ma solo una mancanza di funzionalità nella classe di stringhe.

Se è davvero necessario, è possibile utilizzare una delle soluzioni proposte o creare una classe propria che implementa l'interfaccia IFormattable.

+0

grazie! hai decisamente ragione è la classe di stringhe a cui manca qualcosa. ma hai usato xxx come esempio di qualche formato o significa veramente qualcosa (ad esempio 3 caratteri)? –

+0

@matti, no xxx era solo un esempio. In realtà, ciò che significa è deciso dall'implementazione dell'interfaccia IFormattable. Ad ogni modo (parlando come un amante del C++), la formattazione delle stringhe in C++ rispetto a quella in C# * fa schifo *, parlando di un difetto per il fatto che questa particolare caratteristica manca mi sembra piuttosto strana;) –

0

Non puoi semplicemente applicare argomenti di lunghezza utilizzando il parametro piuttosto che il formato?

String.Format ("-> {0} < -", toFormat.PadRight (10)); // -> Ciao < -

Oppure scrivi il tuo formattatore per permetterti di fare questo?

+0

c commenti alla domanda –

0

Perché non usare solo Substr per limitare la lunghezza della stringa?

String s = "abcdefghijklmnopqrstuvwxyz"; 
String.Format("Character limited: {0}", s.Substr(0, 10)); 
+0

c commenti alla domanda –

+0

Ho perso il fatto che anche Substr ha qualche implementazione scomoda diversa da ogni altra lingua. Ho usato questo workaround così com'è e fallisce, quando la stringa è più corta di 10 caratteri ... –

0

Ho scritto un formattatore personalizzato che implementa un identificatore di formato "L" utilizzato per impostare la larghezza massima. Ciò è utile quando è necessario controllare la dimensione del nostro output formattato dire quando è destinato a una colonna del database o al campo Dynamics CRM.

public class StringFormatEx : IFormatProvider, ICustomFormatter 
{ 
    /// <summary> 
    /// ICustomFormatter member 
    /// </summary> 
    public string Format(string format, object argument, IFormatProvider formatProvider) 
    { 
     #region func-y town 
     Func<string, object, string> handleOtherFormats = (f, a) => 
     { 
      var result = String.Empty; 
      if (a is IFormattable) { result = ((IFormattable)a).ToString(f, CultureInfo.CurrentCulture); } 
      else if (a != null) { result = a.ToString(); } 
      return result; 
     }; 
     #endregion 

     //reality check. 
     if (format == null || argument == null) { return argument as string; } 

     //perform default formatting if arg is not a string. 
     if (argument.GetType() != typeof(string)) { return handleOtherFormats(format, argument); } 

     //get the format specifier. 
     var specifier = format.Substring(0, 1).ToUpper(CultureInfo.InvariantCulture); 

     //perform extended formatting based on format specifier. 
     switch(specifier) 
     { 
      case "L": 
       return LengthFormatter(format, argument); 
      default: 
       return handleOtherFormats(format, argument); 
     } 
    } 

    /// <summary> 
    /// IFormatProvider member 
    /// </summary> 
    public object GetFormat(Type formatType) 
    { 
     if (formatType == typeof(ICustomFormatter)) 
      return this; 
     else 
      return null; 
    } 

    /// <summary> 
    /// Custom length formatter. 
    /// </summary> 
    private string LengthFormatter(string format, object argument) 
    { 
     //specifier requires length number. 
     if (format.Length == 1) 
     { 
      throw new FormatException(String.Format("The format of '{0}' is invalid; length is in the form of Ln where n is the maximum length of the resultant string.", format)); 
     } 

     //get the length from the format string. 
     int length = int.MaxValue; 
     int.TryParse(format.Substring(1, format.Length - 1), out length); 

     //returned the argument with length applied. 
     return argument.ToString().Substring(0, length); 
    } 
} 

L'uso è

var result = String.Format(
    new StringFormatEx(), 
    "{0:L4} {1:L7}", 
    "Stack", 
    "Overflow"); 

Assert.AreEqual("Stac Overflo", result); 
0

Questa non è una risposta su come utilizzare String.Format, ma un altro modo di accorciare una stringa utilizzando metodi di estensione. In questo modo è possibile aggiungere direttamente la lunghezza massima alla stringa, anche senza string.format.

public static class ExtensionMethods 
{ 
    /// <summary> 
    /// Shortens string to Max length 
    /// </summary> 
    /// <param name="input">String to shortent</param> 
    /// <returns>shortened string</returns> 
    public static string MaxLength(this string input, int length) 
    { 
     if (input == null) return null; 
     return input.Substring(0, Math.Min(length, input.Length)); 
    } 
} 

campione utilizzo:

string Test = "1234567890"; 
string.Format("Shortened String = {0}", Test.MaxLength(5)); 
string.Format("Shortened String = {0}", Test.MaxLength(50)); 

Output: 
Shortened String = 12345 
Shortened String = 1234567890 
Problemi correlati