Monday, February 13, 2012

4.4.8. A string we can modify: StringBuilder

If we need to modify a text, letter by letter, we can not use a conventional "string", we need to use a "StringBuilder", which allows it but is a bit more complex to handle: we need to allocate space with the command "new" (as we did for Arrays), and they can be converted to a "conventional" string  using "ToString":

/*---------------------------*/
/*  C# Example #44:          */
/*  example44.cs             */
/*                           */
/*  "StringBuilder"          */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/

using System;
using System.Text; // We will use System.Text.StringBuilder

public class Example44
{

  public static void Main()
  {
    StringBuilder modifiedString = new StringBuilder("Hello");
    modifiedString[1] = 'a';
    Console.WriteLine("Modified string: {0}",
      modifiedString);
   
    string usualString;
    usualString = modifiedString.ToString();
    Console.WriteLine("Conventional string obtained from it: {0}",
      usualString);     
  }
}


Suggested exercises:
·       A program that asks for your name, your birth day and your birth month and gather sit all in a string, separating the name of the date with a comma and the day of the month with a slash, like this: "John, born 31/12 ".
·       A hangman game, in which a first user enters the word to guess, the program displays it hidden under dashes (-----) and the program accepts the letters that a second user enters, changing the dashes for the correct letters (for example, a---at-). The game ends when the user finds the right word or he runs out of attempts (8 maximum).

No comments:

Post a Comment