Format a string -- String.Format()

Format a string -- System.String.Format()


System.String.Format() can format a string with variables.
syntax:
{idx,alignment:formatString}


parameter:

idx: the index of the variable which is matched.
alignment: alignment for the string, it can determine the string will be left-aligned or right-aligned ...etc.
formatString: target, what string want to be formatted.

t

e.g.1
//C#
 static void Main(string[] args)
        {
            int age = 20;
            int score = 100;
            int height = 160;
            Console.WriteLine("{0} {1}",age,score);
        }
/*
output:
20 100
*/
e.g.2
//C#
 static void Main(string[] args)
        {
            int age = 20;
            int score = 100;
            int height = 160;
            Console.WriteLine("{0} {1} {2}",age,score);
        }
/*
exception System.FormatException
because idx 2 can not be matched.
*/
e.g.3
//C#
 static void Main(string[] args)
        {
            
            int age = 20;
            int score = 100;
            int height = 160;
            Console.WriteLine("{0} ",age,score);
        }
/*
output:
20
*/
e.g.4
//C#
 static void Main(string[] args)
        {
            int age = 20;
            int score = 100;
            int height = 160;
            Console.WriteLine("{0} {2}",age,score);
        }
/*
exception System.FormatException
because idx 1 was not exist.
*/

NOTE:
(1)idx must be start from 0 then 1 , 2  , 3 , ... sequencely. 
If the idx is not start from 0, visual studio will throw an exception System.FormatException when I run the project.
(2)If the idx is not increment 1 from the previous idx, visual studio also will throw an exception System.FormatException when I run the project.
(3)Because idx will match the variable, the number of variable in formatted string must be equal to or greater than total number of idx. Or, it can not be matched completely.
In my visual studio project, visual studio will throw an exception System.FormatException when I run the project.



Comments

Popular posts from this blog

String Interpolation(字串內插)