📜  StringFormat C# (1)

📅  最后修改于: 2023-12-03 14:47:43.934000             🧑  作者: Mango

StringFormat in C#

Introduction

StringFormat is a method in C# that helps to format a string. It is a useful method that can be used to manipulate or format the string according to user requirements.

Syntax

The syntax of StringFormat is quite simple. It takes a format string followed by zero or more arguments that are used to format the string.

string str = string.Format("Hello {0}", "world");

In the above example, {0} represents the first argument passed after the format string, which is "world". The result of the above code will be "Hello world".

Some examples of StringFormat are:

string str1= string.Format("{0:C}", 1234.56);
string str2= string.Format("{0:D6}", 123);
string str3= string.Format("{0:F2}", 1234.56);
String Format Specifiers

String format specifiers are used to format a string in a specific way. There are many different format specifiers in C#, some of those are:

  • {0} - The index of the object argument.
  • {0:SomeFormatSpecifier} - The format specifier.
  • {0:C} - Currency format specifier.
  • {0:D} - Decimal format specifier.
  • {0:E} - Exponential format specifier.
  • {0:F} - Fixed-point format specifier.
  • {0:G} - General format specifier.
  • {0:N} - Number format specifier.
  • {0:P} - Percentage format specifier.
  • {0:X} - Hexadecimal format specifier.
Conclusion

StringFormat is a useful method in C# that helps to format a string. With the use of String Format Specifiers, we can format strings in different ways.