Wednesday, 4 June 2014

C# Tutorial-Basics- String Formatting

Building strings from variables is a very common task in programming. 
C# has the string.Format() method to format strings.
Some dynamic languages like Perl, PHP or Ruby support variable interpolation. 
Variable interpolation is replacing variables with their values inside string literals.
 C# does not allow this. It has string formatting instead.
using System;

public class StringFormatting
{
    static void Main()
    {
        int age = 34;
        string name = "Kshatriya";
        string output;

        output = string.Format("{0} is {1} years old.", 
            name, age);
        Console.WriteLine(output);
    }
}
Strings are immutable in C#.
We cannot modify an existing string. 
We must create a new string from existing strings and other types. 
In the code example, we create a new string. We also use values from two variables.

int age = 34;
string name = "Kshatriya";
string output;
Here we declare three variables.

output = string.Format("{0} is {1} years old.", 
    name, age);
We use the Format() method of the built-in string class. 
The {0}, {1} are the places where the variables are evaluated. 
The numbers represent the position of the variable. 
The {0} evaluates to the first supplied variable and the {1} to the second etc.
$ ./stringformatting.exe 
William is 34 years old.
This is the output of the stringformatting.exe program.

No comments:

Post a Comment