Menu ▼



Posted By :
avatarmrkraju
Total Views : 305

Format string using String.Format in C#

String.Format will returns a formatted result string. It converts the value of objects to string based on the format specified. In this example we will see how to format strings using String.Format

Example 1: Format string

string strMessage = string.Format("Hello {0} {1}. Welcome to DotnetLearners.com", txtFirstName.Text, txtLastName.Text);

Where "Hello {0} {1}. Welcome to DotnetLearners.com" is format and txtFirstName.Text, txtLastName.Text are string parameters.

The {} in the format string is format item. and 0, 1 indecates the index of the object whose string value will be inserted at that position.
Output
Hello Will Smith. Welcome to DotnetLearners.com


Example 2: Padding(Adding spaces) string

string strMessage = string.Format("Hello {0, 10} {1, -20}. Welcome to DotnetLearners.com", txtFirstName.Text, txtLastName.Text);

{0, 10} -> indicates 10 characters string (including input string) and the input string will be right aligned, that is spaces will be added left to the string.
{1, -20} -> indicates 20 characters string (including input string) and the input string will be left aligned, that is spaces will be added right to the string.
Output
Hello Will Smith . Welcome to DotnetLearners.com






comments powered by Disqus


Search dotnetlearners.com