+ 1
C# {0}
I was looking at C# playing with but when I put a {1} instead of a {0} it said the code failed, and I just want to know the importance and why it does that. Ex. name = Console.ReadLine() Console.WriteLine("Hello {0}", name) Output Hello (inputted name) name = Console.ReadLine() Console.WriteLine("Hello {0}", name) Output ID-10T 3RR0R
3 ответов
+ 1
name = Console.ReadLine()
Console.WriteLine("Hello {0}", name) ;
After the string "Hello {0}" are a list of arguments to be replaced in the string at respective positions..
Indexes are starts from 0
{n} is just replaced by n'th argument passed.
If you put {1} , instead of {0} in above code, then it's error because you have only one argument but trying to access (1+1) second argument...
Try this :
name = Console.ReadLine()
Console.WriteLine("Hello {0} {1} {2} {3} " , name, "first", " Second", "third");
Hope it helps..
2nd also works.. You may be about "Hello {1} "?
+ 1
It's an example to demonstrate this Farmating :
Try to run this and see output.
It outputs :
"Hello (inputted name) first second third"
I just using string literals (values) directly, than using variables
{0} is replaced by your input into name
{1} is replaced by "first"
{2} is replaced by "second"
{3} is replaced by "third"
If you place {4} or {any 3+ number}, it give error because there only 4 numbers passed.. {0} to {3} are valid.
Hope it clears.
0
Yes sorry, that was a typo, can u explain more on the
Console.WriteLine(“Hello{0}{1}{2}{3}”, name, “first”, “second”, “third”);
Like how it would look with an example input