C# Language
String.Format
Ricerca…
introduzione
I metodi Format sono una serie di overload nella classe System.String utilizzata per creare stringhe che combinano oggetti in rappresentazioni di stringa specifiche. Queste informazioni possono essere applicate a String.Format , a vari metodi WriteLine e ad altri metodi nel framework .NET.
Sintassi
- string.Format (formato stringa, oggetto params [] args)
- string.Format (provider IFormatProvider, formato stringa, oggetto params [] args)
- $ "stringa {testo} blablabla" // Poiché C # 6
Parametri
| Parametro | Dettagli |
|---|---|
| formato | Una stringa di formato composita , che definisce il modo in cui gli argomenti devono essere combinati in una stringa. |
| args | Una sequenza di oggetti da combinare in una stringa. Poiché utilizza un argomento params , puoi utilizzare un elenco di argomenti separato da virgola o un array di oggetti effettivo. |
| fornitore | Una raccolta di modi per formattare gli oggetti alle stringhe. I valori tipici includono CultureInfo.InvariantCulture and CultureInfo.CurrentCulture . |
Osservazioni
Gli appunti:
-
String.Format()gestisce gli argomentinullsenzaString.Format()un'eccezione. - Esistono sovraccarichi che sostituiscono il parametro
argscon uno, due o tre parametri dell'oggetto.
Luoghi in cui String.Format è "incorporato" nel framework
Esistono diversi punti in cui è possibile utilizzare String.Format indirettamente : il segreto è cercare il sovraccarico con il string format, params object[] args firma string format, params object[] args , ad esempio:
Console.WriteLine(String.Format("{0} - {1}", name, value));
Può essere sostituito con una versione più corta:
Console.WriteLine("{0} - {1}", name, value);
Esistono altri metodi che usano anche String.Format ad esempio:
Debug.WriteLine(); // and Print()
StringBuilder.AppendFormat();
Utilizzando il formato numerico personalizzato
NumberFormatInfo può essere utilizzato per formattare sia numeri interi che numeri a virgola mobile.
// invariantResult is "1,234,567.89"
var invarianResult = string.Format(CultureInfo.InvariantCulture, "{0:#,###,##}", 1234567.89);
// NumberFormatInfo is one of classes that implement IFormatProvider
var customProvider = new NumberFormatInfo
{
NumberDecimalSeparator = "_NS_", // will be used instead of ','
NumberGroupSeparator = "_GS_", // will be used instead of '.'
};
// customResult is "1_GS_234_GS_567_NS_89"
var customResult = string.Format(customProvider, "{0:#,###.##}", 1234567.89);
Creare un fornitore di formato personalizzato
public class CustomFormat : IFormatProvider, ICustomFormatter
{
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if (!this.Equals(formatProvider))
{
return null;
}
if (format == "Reverse")
{
return String.Join("", arg.ToString().Reverse());
}
return arg.ToString();
}
public object GetFormat(Type formatType)
{
return formatType==typeof(ICustomFormatter) ? this:null;
}
}
Uso:
String.Format(new CustomFormat(), "-> {0:Reverse} <-", "Hello World");
Produzione:
-> dlroW olleH <-
Allinea a sinistra / a destra, pad con spazi
Il secondo valore nelle parentesi graffe determina la lunghezza della stringa di sostituzione. Regolando il secondo valore come positivo o negativo, è possibile modificare l'allineamento della stringa.
string.Format("LEFT: string: ->{0,-5}<- int: ->{1,-5}<-", "abc", 123);
string.Format("RIGHT: string: ->{0,5}<- int: ->{1,5}<-", "abc", 123);
Produzione:
LEFT: string: ->abc <- int: ->123 <-
RIGHT: string: -> abc<- int: -> 123<-
Formati numerici
// Integral types as hex
string.Format("Hexadecimal: byte2: {0:x2}; byte4: {0:X4}; char: {1:x2}", 123, (int)'A');
// Integers with thousand separators
string.Format("Integer, thousand sep.: {0:#,#}; fixed length: >{0,10:#,#}<", 1234567);
// Integer with leading zeroes
string.Format("Integer, leading zeroes: {0:00}; ", 1);
// Decimals
string.Format("Decimal, fixed precision: {0:0.000}; as percents: {0:0.00%}", 0.12);
Produzione:
Hexadecimal: byte2: 7b; byte4: 007B; char: 41
Integer, thousand sep.: 1,234,567; fixed length: > 1,234,567<
Integer, leading zeroes: 01;
Decimal, fixed precision: 0.120; as percents: 12.00%
Formattazione della valuta
L'identificatore di formato "c" (o valuta) converte un numero in una stringa che rappresenta un importo in valuta.
string.Format("{0:c}", 112.236677) // $112.23 - defaults to system
Precisione
Il valore predefinito è 2. Usa c1, c2, c3 e così via per controllare la precisione.
string.Format("{0:C1}", 112.236677) //$112.2
string.Format("{0:C3}", 112.236677) //$112.237
string.Format("{0:C4}", 112.236677) //$112.2367
string.Format("{0:C9}", 112.236677) //$112.236677000
Simbolo di valuta
- Passa l'istanza di
CultureInfoper usare il simbolo di cultura personalizzato.
string.Format(new CultureInfo("en-US"), "{0:c}", 112.236677); //$112.24
string.Format(new CultureInfo("de-DE"), "{0:c}", 112.236677); //112,24 €
string.Format(new CultureInfo("hi-IN"), "{0:c}", 112.236677); //₹ 112.24
- Usa qualsiasi stringa come simbolo di valuta. Usa
NumberFormatInfoper personalizzare il simbolo di valuta.
NumberFormatInfo nfi = new CultureInfo( "en-US", false ).NumberFormat;
nfi = (NumberFormatInfo) nfi.Clone();
nfi.CurrencySymbol = "?";
string.Format(nfi, "{0:C}", 112.236677); //?112.24
nfi.CurrencySymbol = "?%^&";
string.Format(nfi, "{0:C}", 112.236677); //?%^&112.24
Posizione del simbolo di valuta
Utilizzare CurrencyPositivePattern per i valori positivi e CurrencyNegativePattern per i valori negativi.
NumberFormatInfo nfi = new CultureInfo( "en-US", false ).NumberFormat;
nfi.CurrencyPositivePattern = 0;
string.Format(nfi, "{0:C}", 112.236677); //$112.24 - default
nfi.CurrencyPositivePattern = 1;
string.Format(nfi, "{0:C}", 112.236677); //112.24$
nfi.CurrencyPositivePattern = 2;
string.Format(nfi, "{0:C}", 112.236677); //$ 112.24
nfi.CurrencyPositivePattern = 3;
string.Format(nfi, "{0:C}", 112.236677); //112.24 $
L'utilizzo del pattern negativo è lo stesso del pattern positivo. Molto più casi d'uso si prega di fare riferimento al link originale.
Separatore decimale personalizzato
NumberFormatInfo nfi = new CultureInfo( "en-US", false ).NumberFormat;
nfi.CurrencyPositivePattern = 0;
nfi.CurrencyDecimalSeparator = "..";
string.Format(nfi, "{0:C}", 112.236677); //$112..24
Dal momento che C # 6.0
Dal momento che C # 6.0 è possibile utilizzare l'interpolazione delle stringhe al posto di String.Format .
string name = "John";
string lastname = "Doe";
Console.WriteLine($"Hello {name} {lastname}!");
Ciao John Doe!
Altri esempi di questo argomento sono disponibili nell'argomento C # 6.0: Interpolazione di stringhe .
Sfuggire parentesi graffe all'interno di un'espressione String.Format ()
string outsidetext = "I am outside of bracket";
string.Format("{{I am in brackets!}} {0}", outsidetext);
//Outputs "{I am in brackets!} I am outside of bracket"
Formattazione della data
DateTime date = new DateTime(2016, 07, 06, 18, 30, 14);
// Format: year, month, day hours, minutes, seconds
Console.Write(String.Format("{0:dd}",date));
//Format by Culture info
String.Format(new System.Globalization.CultureInfo("mn-MN"),"{0:dddd}",date);
Console.Write($"{date:ddd}");
produzione :
06
Лхагва
06
| specifier | Senso | Campione | Risultato |
|---|---|---|---|
| d | Data | {0:d} | 2016/07/06 |
| dd | Giorno, zero imbottito | {0:dd} | 06 |
| ddd | Nome del giorno breve | {0:ddd} | sposare |
| dddd | Nome per l'intera giornata | {0:dddd} | mercoledì |
| D | Un appuntamento lungo | {0:D} | Mercoledì 6 luglio 2016 |
| f | Data e ora completi, a breve | {0:f} | Mercoledì 6 luglio 2016 18.30 |
| ff | Seconda frazione, 2 cifre | {0:ff} | 20 |
| F F F | Seconda frazione, 3 cifre | {0:fff} | 201 |
| ffff | Seconda frazione, 4 cifre | {0:ffff} | 2016 |
| F | Data e ora complete, lunghe | {0:F} | Mercoledì 6 luglio 2016 6:30:14 PM |
| g | Data e ora predefinite | {0:g} | 7/6/2016 6:30 PM |
| gg | Era | {0:gg} | ANNO DOMINI |
| hh | Ora (2 cifre, 12 ore) | {0:hh} | 06 |
| HH | Ora (2 cifre, 24 ore) | {0:HH} | 18 |
| M | Mese e giorno | {0:M} | 6 luglio |
| mm | Minuti, senza riempimento | {0:mm} | 30 |
| MM | Mese, riempito a zero | {0:MM} | 07 |
| MMM | Nome del mese di 3 lettere | {0:MMM} | luglio |
| MMMM | Nome completo del mese | {0:MMMM} | luglio |
| ss | secondi | {0:ss} | 14 |
| r | Data RFC1123 | {0:r} | Mer, 06 lug 2016 18:30:14 GMT |
| S | Stringa di data ordinabile | {0:s} | 2016-07-06T18: 30: 14 |
| t | Poco tempo | {0:t} | 6:30 PM |
| T | A lungo | {0:T} | 6:30:14 PM |
| TT | AM PM | {0:tt} | PM |
| u | Ora locale ordinabile universale | {0:u} | 18-07-2016 18: 30: 14Z |
| U | GMT universale | {0:U} | Mercoledì 6 luglio 2016 9:30:14 |
| Y | Mese e anno | {0:Y} | Luglio 2016 |
| aa | Anno 2 cifre | {0:yy} | 16 |
| aaaa | Anno 4 cifre | {0:yyyy} | 2016 |
| zz | Offset fuso orario a 2 cifre | {0:zz} | +09 |
| zzz | offset fuso orario completo | {0:zzz} | +09: 00 |
Accordare()
Il metodo ToString () è presente su tutti i tipi di oggetti di riferimento. Ciò è dovuto al fatto che tutti i tipi di riferimento derivano da Object su cui è presente il metodo ToString (). Il metodo ToString () sulla classe base dell'oggetto restituisce il nome del tipo. Il frammento seguente stamperà "Utente" sulla console.
public class User
{
public string Name { get; set; }
public int Id { get; set; }
}
...
var user = new User {Name = "User1", Id = 5};
Console.WriteLine(user.ToString());
Tuttavia, la classe User può anche sovrascrivere ToString () per modificare la stringa restituita. Il frammento di codice sottostante stampa "Id: 5, Name: User1" sulla console.
public class User
{
public string Name { get; set; }
public int Id { get; set; }
public override ToString()
{
return string.Format("Id: {0}, Name: {1}", Id, Name);
}
}
...
var user = new User {Name = "User1", Id = 5};
Console.WriteLine(user.ToString());
Relazione con ToString ()
Mentre il metodo String.Format() è certamente utile per la formattazione dei dati come stringhe, può spesso essere un po 'eccessivo, specialmente quando si ha a che fare con un singolo oggetto come mostrato di seguito:
String.Format("{0:C}", money); // yields "$42.00"
Un approccio più semplice potrebbe essere quello di utilizzare semplicemente il metodo ToString() disponibile su tutti gli oggetti all'interno di C #. Supporta tutte le stesse stringhe di formattazione standard e personalizzate , ma non richiede la mappatura dei parametri necessaria in quanto ci sarà un solo argomento:
money.ToString("C"); // yields "$42.00"
Avvertenze e restrizioni alla formattazione
Sebbene questo approccio possa essere più semplice in alcuni scenari, l'approccio ToString() è limitato per quanto riguarda l'aggiunta del String.Format() sinistro o destro come si farebbe nel metodo String.Format() :
String.Format("{0,10:C}", money); // yields " $42.00"
Per ottenere lo stesso comportamento con il metodo ToString() , è necessario utilizzare un altro metodo come PadLeft() o PadRight() rispettivamente:
money.ToString("C").PadLeft(10); // yields " $42.00"