If you remember the lesson about char variable type, you know that a char can only store a single character. And you also remember that for storing more than a single character, I said you will be using the string variable type.
A string is basically a series of one or more characters. It’s default value is null. Unlike characters, which enclose their value between single quotation marks, strings enclose them in double quotation marks.
Lets see an example about declaring and initializing a string variable type:
1 2 3 4 5 6 7 8 9 10 11 12 |
static void Main(string[] args) { // Declare some variables string firstName = "John"; string lastName = "Smith"; string fullName = firstName + " " + lastName; // Print the results on the console Console.WriteLine("Hello, " + firstName + "!"); Console.WriteLine("Your full name is " + fullName + "."); Console.Read(); } |
The output of the above code will be this:
Various text-processing operations can be performed using strings: concatenation (joining one string with another), splitting by a given separator, searching, replacement of characters and others. I will be explaining all them in a later part of our lessons.
The concepts explained in this lesson are also shown visually as part of the following video:
EXERCISES
1. Declare two variables of type string with values “Hello” and “World”. Declare another variable of type string and assign to it the value obtained from concatenation of the two string variables (add space if necessary). Print the third string variable on console.
Solution
2. A company dealing with marketing wants to keep a data record of its employees. Each record should have the following characteristic – first name, last name, age, gender (‘m’ or ‘f’), and unique employee number (27560000 to 27569999). Declare appropriate variables needed to maintain the information for an employee by using the appropriate data types and attribute names. Solution
For the names use type string, for the gender use type char (only one char m/f), and for the unique number and age use some integer type.