StringBuilder.AppendFormat Method (System.Text) (original) (raw)
Source:
Source:
Source:
Source:
Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Each format item is replaced by the string representation of a corresponding argument in a parameter array using a specified format provider.
public:
System::Text::StringBuilder ^ AppendFormat(IFormatProvider ^ provider, System::String ^ format, ... cli::array <System::Object ^> ^ args);
public System.Text.StringBuilder AppendFormat(IFormatProvider provider, string format, params object[] args);
public System.Text.StringBuilder AppendFormat(IFormatProvider? provider, string format, params object?[] args);
member this.AppendFormat : IFormatProvider * string * obj[] -> System.Text.StringBuilder
Public Function AppendFormat (provider As IFormatProvider, format As String, ParamArray args As Object()) As StringBuilder
Parameters
provider
An object that supplies culture-specific formatting information.
format
A composite format string.
args
Object[]
An array of objects to format.
Returns
A reference to this instance after the append operation has completed. After the append operation, this instance contains any data that existed before the operation, suffixed by a copy of format
where any format specification is replaced by the string representation of the corresponding object argument.
Exceptions
format
is invalid.
-or-
The index of a format item is less than 0 (zero), or greater than or equal to the length of the args
array.
The length of the expanded string would exceed MaxCapacity.
Examples
The following example demonstrates the AppendFormat method.
using System;
using System.Text;
using System.Globalization;
class Sample
{
static StringBuilder sb = new StringBuilder();
public static void Main()
{
int var1 = 111;
float var2 = 2.22F;
string var3 = "abcd";
object[] var4 = {3, 4.4, 'X'};
Console.WriteLine();
Console.WriteLine("StringBuilder.AppendFormat method:");
sb.AppendFormat("1) {0}", var1);
Show(sb);
sb.AppendFormat("2) {0}, {1}", var1, var2);
Show(sb);
sb.AppendFormat("3) {0}, {1}, {2}", var1, var2, var3);
Show(sb);
sb.AppendFormat("4) {0}, {1}, {2}", var4);
Show(sb);
CultureInfo ci = new CultureInfo("es-ES", true);
sb.AppendFormat(ci, "5) {0}", var2);
Show(sb);
}
public static void Show(StringBuilder sbs)
{
Console.WriteLine(sbs.ToString());
sb.Length = 0;
}
}
/*
This example produces the following results:
StringBuilder.AppendFormat method:
1) 111
2) 111, 2.22
3) 111, 2.22, abcd
4) 3, 4.4, X
5) 2,22
*/
open System.Text
open System.Globalization
let sb = StringBuilder()
let show (sbs: StringBuilder) =
printfn $"{sbs}"
sb.Length <- 0
let var1 = 111
let var2 = 2.22f
let var3 = "abcd"
let var4: obj[] = [| 3; 4.4; 'X' |]
printfn "StringBuilder.AppendFormat method:"
sb.AppendFormat("1) {0}", var1) |> ignore
show sb
sb.AppendFormat("2) {0}, {1}", var1, var2) |> ignore
show sb
sb.AppendFormat("3) {0}, {1}, {2}", var1, var2, var3) |> ignore
show sb
sb.AppendFormat("4) {0}, {1}, {2}", var4) |> ignore
show sb
let ci = CultureInfo("es-ES", true)
sb.AppendFormat(ci, "5) {0}", var2) |> ignore
show sb
// This example produces the following results:
// StringBuilder.AppendFormat method:
// 1) 111
// 2) 111, 2.22
// 3) 111, 2.22, abcd
// 4) 3, 4.4, X
// 5) 2,22
Imports System.Text
Imports System.Globalization
Class Sample
Private Shared sb As New StringBuilder()
Public Shared Sub Main()
Dim var1 As Integer = 111
Dim var2 As Single = 2.22F
Dim var3 As String = "abcd"
Dim var4 As Object() = {3, 4.4, "X"c}
Console.WriteLine()
Console.WriteLine("StringBuilder.AppendFormat method:")
sb.AppendFormat("1) {0}", var1)
Show(sb)
sb.AppendFormat("2) {0}, {1}", var1, var2)
Show(sb)
sb.AppendFormat("3) {0}, {1}, {2}", var1, var2, var3)
Show(sb)
sb.AppendFormat("4) {0}, {1}, {2}", var4)
Show(sb)
Dim ci As New CultureInfo("es-ES", True)
sb.AppendFormat(ci, "5) {0}", var2)
Show(sb)
End Sub
Public Shared Sub Show(sbs As StringBuilder)
Console.WriteLine(sbs.ToString())
sb.Length = 0
End Sub
End Class
'
'This example produces the following results:
'
'StringBuilder.AppendFormat method:
'1) 111
'2) 111, 2.22
'3) 111, 2.22, abcd
'4) 3, 4.4, X
'5) 2,22
The following example defines a custom IFormatProvider implementation named CustomerFormatter
that formats a 10-digit customer number with hyphens after the fourth and seventh digits. It is passed to the StringBuilder.AppendFormat(IFormatProvider, String, Object[]) method to create a string that includes the formatted customer number and customer name.
using System;
using System.Text;
public class Customer
{
private string custName;
private int custNumber;
public Customer(string name, int number)
{
this.custName = name;
this.custNumber = number;
}
public string Name
{
get { return this.custName; }
}
public int CustomerNumber
{
get { return this.custNumber; }
}
}
public class CustomerNumberFormatter : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
return null;
}
public string Format(string format, object arg, IFormatProvider provider)
{
if (arg is Int32)
{
string custNumber = ((int) arg).ToString("D10");
return custNumber.Substring(0, 4) + "-" + custNumber.Substring(4, 3) +
"-" + custNumber.Substring(7, 3);
}
else
{
return null;
}
}
}
public class Example
{
public static void Main()
{
Customer customer = new Customer("A Plus Software", 903654);
StringBuilder sb = new StringBuilder();
sb.AppendFormat(new CustomerNumberFormatter(), "{0}: {1}",
customer.CustomerNumber, customer.Name);
Console.WriteLine(sb.ToString());
}
}
// The example displays the following output:
// 0000-903-654: A Plus Software
open System
open System.Text
type Customer(name: string, number: int) =
member _.Name = name
member _.CustomerNumber = number
type CustomerNumberFormatter() =
interface IFormatProvider with
member this.GetFormat(formatType) =
if formatType = typeof<ICustomFormatter> then this else null
interface ICustomFormatter with
member _.Format(_, arg, _) =
match arg with
| :? int as i ->
let custNumber = i.ToString "D10"
$"{custNumber.Substring(0, 4)}-{custNumber.Substring(4, 3)}-{custNumber.Substring(7, 3)}"
| _ -> null
let customer = Customer("A Plus Software", 903654)
let sb = StringBuilder()
sb.AppendFormat(CustomerNumberFormatter(), "{0}: {1}", customer.CustomerNumber, customer.Name)
|> ignore
printfn $"{sb}"
// The example displays the following output:
// 0000-903-654: A Plus Software
Imports System.Text
Public Class Customer
Private custName As String
Private custNumber As Integer
Public Sub New(name As String, number As Integer)
custName = name
custNumber = number
End Sub
Public ReadOnly Property Name As String
Get
Return Me.custName
End Get
End Property
Public ReadOnly Property CustomerNumber As Integer
Get
Return Me.custNumber
End Get
End Property
End Class
Public Class CustomerNumberFormatter
Implements IFormatProvider, ICustomFormatter
Public Function GetFormat(formatType As Type) As Object _
Implements IFormatProvider.GetFormat
If formatType Is GetType(ICustomFormatter) Then
Return Me
End If
Return Nothing
End Function
Public Function Format(fmt As String, arg As Object, provider As IFormatProvider) As String _
Implements ICustomFormatter.Format
If typeof arg Is Int32 Then
Dim custNumber As String = CInt(arg).ToString("D10")
Return custNumber.Substring(0, 4) + "-" + custNumber.SubString(4, 3) + _
"-" + custNumber.Substring(7, 3)
Else
Return Nothing
End If
End Function
End Class
Module Example
Public Sub Main()
Dim customer As New Customer("A Plus Software", 903654)
Dim sb As New StringBuilder()
sb.AppendFormat(New CustomerNumberFormatter, "{0}: {1}", _
customer.CustomerNumber, customer.Name)
Console.WriteLine(sb.ToString())
End Sub
End Module
' The example displays the following output:
' 0000-903-654: A Plus Software
Remarks
This method uses the composite formatting feature of the .NET Framework to convert the value of an object to its text representation and embed that representation in the current StringBuilder object.
The format
parameter consists of zero or more runs of text intermixed with zero or more indexed placeholders, called format items, that correspond to objects in the parameter list of this method. The formatting process replaces each format item with the string representation of the corresponding object.
The syntax of a format item is as follows:
{_index_[,_length_][:_formatString_]}
Elements in square brackets are optional. The following table describes each element.
Element | Description |
---|---|
index | The zero-based position in the parameter list of the object to be formatted. If the object specified by index is null, the format item is replaced by String.Empty. If there is no parameter in the index position, a FormatException is thrown. |
,length | The minimum number of characters in the string representation of the parameter. If positive, the parameter is right-aligned; if negative, it is left-aligned. |
:formatString | A standard or custom format string that is supported by the parameter. |
The provider
parameter specifies an IFormatProvider implementation that can provide formatting information for the objects in args
. provider
can be any of the following:
- A CultureInfo object that provides culture-specific formatting information.
- A NumberFormatInfo object that provides culture-specific formatting information for numeric values in
args
. - A DateTimeFormatInfo object that provides culture-specific formatting information for date and time values in
args
. - A custom IFormatProvider implementation that provides formatting information for one or more of the objects in
args
. Typically, such an implementation also implements the ICustomFormatter interface. The second example in the next section illustrates an StringBuilder.AppendFormat(IFormatProvider, String, Object[]) method call with a custom IFormatProvider implementation.
If the provider
parameter is null
, format provider information is obtained from the current culture.
args
represents the objects to be formatted. Each format item in format
is replaced with the string representation of the corresponding object in args
. If the format item includes formatString
and the corresponding object in args
implements the IFormattable interface, then args[index].ToString(formatString, provider)
defines the formatting. Otherwise, args[index].ToString()
defines the formatting.
Notes to Callers
In .NET Core and in the .NET Framework 4.0 and later versions, when you instantiate the StringBuilder object by calling the StringBuilder(Int32, Int32) constructor, both the length and the capacity of the StringBuilder instance can grow beyond the value of its MaxCapacity property. This can occur particularly when you call the Append(String) and AppendFormat(String, Object) methods to append small strings.
See also
- Formatting Types in .NET
- Composite Formatting
- How to: Define and Use Custom Numeric Format Providers
- Standard Numeric Format Strings
- Custom Numeric Format Strings
- Standard Date and Time Format Strings
- Custom Date and Time Format Strings
- Standard TimeSpan Format Strings
- Custom TimeSpan Format Strings
- Enumeration Format Strings