Friday, January 27, 2012

3.4. First contact with the strings

Text strings are as easy to handle as other types of data we have seen, with only three differences:
  • They are declared with the word "string". 
  • If we want them to have a starting value, this is indicated in double quotes. 
  • When reading with ReadLine, we do not need convert the obtained value. 
  • We can compare them using "==" and "!=".

Thus, an example to assign a value to a "string", display it (in quotes, to practice the escape sequences we have seen in the previous section) and read a value typed by the user, might be:

/*---------------------------*/
/*  C# Example #31:          */
/*  example31.cs             */
/*                           */
/*  Basic “string” use       */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/

using System;

public class Example31
{
    public static void Main()
    {
        string sentence;
       
        sentence = "Hi, how are you?";
        Console.WriteLine("The sentence is \"{0}\"", sentence);
       
        Console.WriteLine("Enter a new sentence");
        sentence = Console.ReadLine();
        Console.WriteLine("Now the sentence is \"{0}\"", sentence);

        if (sentence == "Hi!")
            Console.WriteLine("Hi again!");
    }
}

We can do many more operations on strings: convert to upper case or lower case, remove spaces, replace one substring with another, split into pieces, and so on. But we'll discuss about that in the next chapter.

Suggested exercises:
·       Write a program that asks the user for his name, and answers "Hi" if he is called "John" or "I don't know you" if he types a different name.
·       Create a program to ask the user for a name and a password. The password must be entered twice. If both passwords are not the same, the user must be warned and the program will ask for both again.

Thursday, January 26, 2012

3.3.1. Escape sequences: \n and others

As we have seen, the on-screen texts are written using WriteLine, delimited with brackets and double quotes. But... how can we write a double quote on the screen? We can use certain special characters, known as "escape sequences". They are written after a backslash (\). For example, \" displays double quotes, and \' a single quote, and \n advances to the next line on screen.

These special sequences are:

Sequence         Meaning
\a                      Beeps (alert)
\b                      Backspace (deleted the last character)
\f                       Form feed (ejects a sheet into the printer)
\n                      New line (jumps to the next line)
\r                      Carriage Return (goes to beginning of line)
\t                       Horizontal tabulation
\v                      Vertical tabulation
\'                       Displays a single quote
\"                      Displays a double quote
\\                      Displays a backslash
\0                      Null character (NULL)

Let's see an example that uses the most common ones:

/*---------------------------*/
/*  C# Example #30:          */
/*  example30.cs             */
/*                           */
/*  Escape sequences         */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/

using System;

public class Example30
{
    public static void Main()
    {
        Console.WriteLine("This is a sentence");
        Console.WriteLine();
        Console.WriteLine();
        Console.WriteLine("and another, two lines apart");
       
        Console.WriteLine("\n\nMore lines apart...\n\nand more");
        Console.WriteLine("Double quotes: \", simple quotes \', slash \\");
    }
}


Which would display:

This is a sentence


and another, two lines apart


More lines apart...

and more
Double quotes: ", simple quotes ', slash \


These escape sequences are sometimes laborious to manipulate. For example, when using a directory structure as: c:\\data\\examples\\course\\example1. In this case, we can use an "at" sign (@) before the text instead of the backslashes:

myPath = @"c:\data\examples\course\example1"

In this case, the problem arises when there are quotes in the middle of the string. To show these quotes, we just double them:

command = @"copy ""example document"" f:"

Suggested exercise:
·         Create a program that asks the user to type five letters and display them on screen together, but in reverse order, and between double quotes. For example if the entered letters are o, l, l, e , h, it should display "hello".

Wednesday, January 25, 2012

3.3. Character data type

We also have a data type to store a single letter. It is named "char":

char letter;

Assigning values is simple: we indicate them using single quotes:

letter = 'a';

If we want to read values from the keyboard, we can make it similar in a similar way to the previous cases: read an entire sentence with ReadLine and convert it using Convert.ToChar:

letter = Convert.ToChar(Console.ReadLine());

A program to assign an starting value to a letter, display it, read a new letter entered by the user, and show it again, might be:

/*---------------------------*/
/*  C# Example #29:          */
/*  example29.cs             */
/*                           */
/*  "char" data type         */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/

using System;

public class Example29
{
    public static void Main()
    {
        char letter;
       
        letter = 'a';
        Console.WriteLine("The letter is {0}", letter);
       
        Console.WriteLine("Enter a new letter");
        letter = Convert.ToChar(Console.ReadLine());
        Console.WriteLine("Now the letter is {0}", letter);
    }
}