In practice we often come to the text processing: reading text files, searching for keywords and replacing them in a paragraph, validating user input data, etc. In such cases we can save the text content, which we will need in strings, and process them using the C# language.
A string is a sequence of characters stored in a certain address in memory. Remember the type char? In the variable of type char we can record only one character. Where it is necessary to process more than one character then strings come to our aid.
We can declare variables from the type string by the following rule:
Declaring a string represents a variable declaration of type string. This is not equivalent to setting a variable and allocating memory for it! With the declaration we inform the compiler that the variable str will be used and the expected type for it is string. We do not create a variable in the memory and it is not available for processing yet (value is null, which means no value).
In order to process the declared string variable, we must create it and initialize it. Creating a variable of certain class (also known as instantiating)
is a process associated with the allocation of the dynamic memory area (the heap). Before setting a specific value to the string, its value is null. This can be confusing to the beginner programmers: uninitialized variables of type string do not contain empty values, it contains the special value null – and
each attempt for manipulating such a string will generate an error (exception for access to a missing value NullReferenceException)!
We can initialize variables in the following three ways:
Setting a string literal means to assign a predefined textual content to a variable of type string. We use this type of initialization, when we know the value that must be stored in the variable. Example for setting a string literal:
string website = "http://www.techbaz.org";
Assigning a value is equivalent to directing a string value or a variable to a variable of type string. An example is the following code snippet:
string name = "AyaN";
string data = name;
The third option to initialize a string is to pass the value of a string expression or operation, which returns a string result. This can be a result
from a method, which validates data; adding together the values of a number of constants and variables; transforming an existing variable, etc.
Example of an expression, which returns a string:
string email = "firstname.lastname@example.org";
string info = "My mail is: " + email;
We adding new programming language tutorials very soon.
We make a Collaboration with HackIsOn YouTube Channel So, Please Subscribe Their Channel and keep supporting