Зміст курсу
C# Basics
C# Basics
Basic String Formatting
String Formatting refers to the process of constructing and customizing textual output. It involves inserting variables and values into a predefined text template. It is useful for creating readable and structured text representations.
We can output text and a variable value using an already known method (the +
operator):
main
However there are better and more suitable methods for string formatting which can also handle complex cases. The first method is by using the placeholder syntax. To understand this syntax we will use the Console.WriteLine method:
main
In the above code we insert placeholders in the string where values are to be inserted. The syntax of a placeholder is a number (index) enclosed in curly brackets ({index}
) and the value index starts from 0
. When the output string is generated, the placeholders are filled with the corresponding values that are passed as additional arguments to the Console.WriteLine method.
The following diagram illustrates the process in an easier to understand way:
Note
Arguments are the values we pass into a function or command. For-example, in
Console.WriteLine("Value: {0}", 100);
, the terms"Value: {0}"
and100
are values.
There is another much simpler method of formatting strings. We can use the $
character to indicate that a string is a formatted string and directly insert values inside it using the curly brackets ({}
):
Using this syntax, we can also generate and store formatted strings into string variables:
main
Все було зрозуміло?