C# string format

The C# string format is used to modify a string. It does so by inserting objects and variables at desired positions.

Syntax

String.Format("anyString {index[,alignment][:formatString]}", object);

anyString: It is an optional string.

index: The position where an object or a variable can be inserted (it always starts with zero). In the case of NULL, an empty string is inserted.

alignment: It is an optional, signed integer used to align a string to the left or right.

formatString: It is also optional; the complete formatting types can be found here.

svg viewer

Code

class Marvel
{
static void Main()
{
string str = "Marvel Characters: {0}, {1}";
string tempStr = string.Format(str, "Thor", "Deadpool");
System.Console.WriteLine(tempStr);
}
}

You can try different alignments and formatting for date, money, and custom formats as well.

Copyright ©2024 Educative, Inc. All rights reserved