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.

No comments:

Post a Comment