Home

The Characters of a String

 

Introduction

To represent the values of an application, we primarily use characters, letters, and symbols from the alphabet or out of the alphabet. To recognize these symbols, the C# language provides the char data type. The char data type is identified in the .NET Framework by the Char structure, which gets represented with a 16-bit value.

To declare a variable that can hold one character, a letter, or a symbol, user the char data type. To initialize the variable, include its value between two single-quotes. Here are examples:

using System;

class Exercise
{
    static int Main(string[] args)
    {
        char Gender = 'm';
        char MoneySymbol = '$';
        char Multiplication = '*';
        char NumberOne = '1';
        
        Console.WriteLine("A few characters");
        Console.WriteLine("Gender:         {0}", Gender);
        Console.WriteLine("Money Symbol:   {0}", MoneySymbol);
        Console.WriteLine("Multiplication: {0}", Multiplication);
        Console.WriteLine("Number One:     {0}", NumberOne);
        
        Console.WriteLine();
        return 0;
    }
}

This would produce:

A few characters
Gender:         m
Money Symbol:   $
Multiplication: *
Number One:     1

Press any key to continue...

 

Practical Learning Practical Learning: Introducing Strings

  1. Start Microsoft Visual C# and create a new Console Application named RealEstate6
  2. To create a new class, on the main menu, click Project -> Add Class...
  3. Set the Name to Property and press Enter
  4. Change the file as follows:
     
    using System;
    
    namespace RealEstate6
    {
        public enum PropertyCondition
        {
            Unknown,
            Excellent,
            Good,
            NeedsRepair,
            BadShape
        }
    
        public class Property
        {
            private string propNbr;
            private PropertyCondition cond;
            private short beds;
            private float baths;
            private int yr;
            private decimal val;
    
            public Property()
            {
            }
    
            public string PropertyNumber
            {
                get { return propNbr; }
                set
                {
                    if (propNbr == "")
                        propNbr = "N/A";
                    else
                        propNbr = value;
                }
            }
    
            public PropertyCondition Condition
            {
                get { return cond; }
                set { cond = value; }
            }
    
            public short Bedrooms
            {
                get
                {
                    if (beds <= 1)
                        return 1;
                    else
                        return beds;
                }
                set { beds = value; }
            }
    
            public float Bathrooms
            {
                get { return (baths <= 0) ? 0.00f : baths; }
                set { baths = value; }
            }
    
            public int YearBuilt
            {
                get { return yr; }
                set { yr = value; }
            }
    
            public decimal Value
            {
                get { return (val <= 0) ? 0.00M : val; }
                set { val = value; }
            }
        }
    }
  5. In the Class View, right-click RealEstate6 -> Add -> Class...
  6. Set the Name to HouseType and press Enter
  7. To derive a class, change the file as follows:
     
    using System;
    
    namespace RealEstate6
    {
        public class HouseType : Property
        {
            private short nbrOfStories;
            private bool basement;
            private bool garage;
    
            public short Stories
            {
                get { return nbrOfStories; }
                set { nbrOfStories = value; }
            }
    
            public bool FinishedBasement
            {
                get { return basement; }
                set { basement = value; }
            }
    
            public bool IndoorGarage
            {
                get { return garage; }
                set { garage = value; }
            }
        }
    }
  8. To create a new class, in the Solution Explorer, right-click RealEstate6, position the mouse on Add and click Class...
  9. Set the Name to Condominium and click Add
  10. To create another class based on the Property class, change the file as follows:
     
    using System;
    
    namespace RealEstate6
    {
        public class Condominium : Property
        {
            private bool handicap;
    
            public bool HandicapAccessible
            {
                get { return handicap; }
                set { handicap = value; }
            }
        }
    }
     
  11. In the Solution Explorer, right- click RealEstate6 -> Add -> Class...
  12. Set the Name to PropertyListing and press Enter
  13. Change the file as follows:
     
    using System;
    
    namespace RealEstate6
    {
        public enum PropertyType
        {
            Unknown,
            SingleFamily,
            Townhouse,
            Condominium
        }
    
        public class PropertyListing
        {
            private Property prop;
            private HouseType hse;
            private Condominium cond;
            private PropertyType tp;
    
            public Property ListProperty
            {
                get { return prop; }
                set { prop = value; }
            }
    
            public HouseType House
            {
                get { return hse; }
                set { hse = value; }
            }
    
            public Condominium Condo
            {
                get { return cond; }
                set { cond = value; }
            }
    
            public PropertyType Type
            {
                get { return tp; }
                set { tp = value; }
            }
    
            public PropertyListing()
            {
                prop = new Property();
                hse = new HouseType();
                cond = new Condominium();
            }
    
            public void CreateListing()
            {
                char answer     = 'n';
                short propType  = 1;
                short condition = 1;
    
                Console.WriteLine(" =//= Altair Realty =//=");
                Console.WriteLine("-=- Property Creation -=-");
                try
                {
                    Console.WriteLine("\nTypes of Properties");
                    Console.WriteLine("1. Single Family");
                    Console.WriteLine("2. Townhouse");
                    Console.WriteLine("3. Condominium");
                    Console.WriteLine("4. Don't Know");
                    Console.Write("Enter Type of Property: ");
                    propType = short.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("The value you entered for the type of property is invalid");
                }
                catch (Exception)
                {
                    Console.WriteLine("A bad behavior has been detectedd");
                }
    
                Console.Write("\nEnter Property #: ");
                ListProperty.PropertyNumber = Console.ReadLine();
    
                try
                {
                    Console.WriteLine("\nProperties Conditions");
                    Console.WriteLine("1. Excellent");
                    Console.WriteLine("2. Good (may need minor repair)");
                    Console.WriteLine("3. Needs Repair");
                    Console.WriteLine("4. In Bad Shape (property needs ");
                    Console.WriteLine("major repair or rebuild)");
                    Console.Write("Enter Property Condition: ");
                    condition = short.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("The value you entered for the condition of the property is not valid");
                }
                catch (Exception)
                {
                    Console.WriteLine("An unacceptable event has just happened");
                }
    
                if (condition == 1)
                    ListProperty.Condition = PropertyCondition.Excellent;
                else if (condition == 2)
                    ListProperty.Condition = PropertyCondition.Good;
                else if (condition == 3)
                    ListProperty.Condition = PropertyCondition.NeedsRepair;
                else if (condition == 4)
                    ListProperty.Condition = PropertyCondition.BadShape;
                else
                    ListProperty.Condition = PropertyCondition.Unknown;
    
                switch ((PropertyType)propType)
                {
                    case PropertyType.SingleFamily:
                        Type = PropertyType.SingleFamily;
                        try
                        {
                            Console.Write("\nHow many stories (levels)? ");
                            House.Stories = short.Parse(Console.ReadLine());
                        }
            catch (FormatException)
            {
                    Console.WriteLine("The number of stories you entered is not allowed");
            }
                        catch (Exception)
                        {
                            Console.WriteLine("An abnormal behavior has occurred");
                        }
    
                        try
                        {
                            Console.Write("Does it have an indoor car garage (y/n): ");
                            answer = char.Parse(Console.ReadLine());
                            if ((answer == 'y') || (answer == 'Y'))
                                House.IndoorGarage = true;
                            else
                                House.IndoorGarage = false;
                        }
                        catch (FormatException)
                        {
                            Console.WriteLine("Invalid Indoor Car Garage Answer");
                        }
                        try
                        {
                            Console.Write("Is the basement finished(y/n): ");
                            answer = char.Parse(Console.ReadLine());
                            if ((answer == 'y') || (answer == 'Y'))
                                House.FinishedBasement = true;
                            else
                                House.FinishedBasement = false;
                        }
                        catch (FormatException)
                        {
                            Console.WriteLine("Invalid Basement Answer");
                        }
                        break;
    
                    case PropertyType.Townhouse:
                        Type = PropertyType.Townhouse;
                        try
                        {
                            Console.Write("\nHow many stories (levels)? ");
                            House.Stories = short.Parse(Console.ReadLine());
                        }
                        catch (FormatException)
                        {
                            Console.WriteLine("The number of stories you entered is not valid");
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("This is one of those abnormal behaviors");
                        }
    
                        Console.Write("Does it have an indoor car garage (y/n): ");
                        answer = char.Parse(Console.ReadLine());
                        if ((answer == 'y') || (answer == 'Y'))
                            House.IndoorGarage = true;
                        else
                            House.IndoorGarage = false;
                        Console.Write("Is the basement finished(y/n): ");
                        answer = char.Parse(Console.ReadLine());
                        if ((answer == 'y') || (answer == 'Y'))
                            House.FinishedBasement = true;
                        else
                            House.FinishedBasement = false;
                        break;
    
                    case PropertyType.Condominium:
                        Type = PropertyType.Condominium;
                        Console.Write("\nIs the building accessible to handicapped (y/n): ");
                        answer = char.Parse(Console.ReadLine());
                        if ((answer == 'y') || (answer == 'Y'))
                            Condo.HandicapAccessible = true;
                        else
                            Condo.HandicapAccessible = false;
                        break;
    
                    default:
                        Type = PropertyType.Unknown;
                        break;
                }
    
                try
                {
                    Console.Write("\nHow many bedrooms?  ");
                    ListProperty.Bedrooms = short.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("The value you entered for the number of bedrooms is not good");
                }
                catch (Exception)
                {
                    Console.WriteLine("The program has decided to stop");
                }
    
                try
                {
                    Console.Write("How many bathrooms? ");
                    ListProperty.Bathrooms = float.Parse(Console.ReadLine());
                }
                catch (Exception)
                {
                    Console.WriteLine("The computer has encountered an error");
                }
    
                try
                {
                    Console.Write("Year built:         ");
                    ListProperty.YearBuilt = int.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("The house cannot have built in that year");
                }
                catch (Exception)
                {
                    Console.WriteLine("The application is experiencing a problem");
                }
    
                try
                {
                    Console.Write("Property Value:     ");
                    ListProperty.Value = decimal.Parse(Console.ReadLine());
                }
                catch (Exception)
                {
                    Console.WriteLine("This is where the application draws the line: it stops!");
                }
            }
    
            public void ShowListing()
            {
                Console.WriteLine("==================================");
                Console.WriteLine(" =//=//= Altair Realty =//=//=");
                Console.WriteLine("-=-=-=- Properties Listing -=-=-=-");
                Console.WriteLine("----------------------------------");
                Console.WriteLine("Property #:            {0}",
                    ListProperty.PropertyNumber);
                Console.WriteLine("Property Type:         {0}", Type);
    
                switch (Type)
                {
                    case PropertyType.SingleFamily:
                    case PropertyType.Townhouse:
                        Type = PropertyType.SingleFamily;
                        Console.WriteLine("Stories:               {0}",
                            House.Stories);
                        Console.WriteLine("Has Indoor Car Garage: {0}",
                            House.IndoorGarage);
                        Console.WriteLine("Finished Basement:     {0}",
                            House.FinishedBasement);
                        break;
    
                    case PropertyType.Condominium:
                        Console.WriteLine("Handicapped Accessible Building: {0}",
                            Condo.HandicapAccessible);
                        break;
                }
    
                Console.WriteLine("Condition:             {0}", ListProperty.Condition);
                Console.WriteLine("Bedrooms:              {0}", ListProperty.Bedrooms);
                Console.WriteLine("Bathrooms:             {0:F}", ListProperty.Bathrooms);
                Console.WriteLine("Year Built:            {0}", ListProperty.YearBuilt);
                Console.WriteLine("Market Value:          {0:C}", ListProperty.Value);
            }
        }
    }
  14. Access the Program.cs file and change it as follows:
     
    using System;
    
    namespace RealEstate6
    {
        class Program
        {
            static int Main()
            {
                PropertyListing listing = new PropertyListing();
    
                listing.CreateListing();
                Console.WriteLine("\n");
                listing.ToString();
                
                return 0;
            }
        }
    }
  15. Execute the application and test it. Here is an example:
     
    =//= Altair Realty =//=
    -=- Property Creation -=-
    
    Types of Properties
    1. Single Family
    2. Townhouse
    3. Condominium
    4. Don't Know
    Enter Type of Property: 1
    
    Enter Property #: 793742
    
    Properties Conditions
    1. Excellent
    2. Good (may need minor repair)
    3. Needs Repair
    4. In Bad Shape (property needs major repair or rebuild)
    Enter Property Condition: 3
    
    How many stories (levels)? 3
    Does it have an indoor car garage (y/n): p
    Is the basement finished(y/n): t
    
    How many bedrooms?  4
    How many bathrooms? 3.5
    Year built:         1994
    Property Value:     658225.85
    
    ==================================
     =//=//= Altair Realty =//=//=
    -=-=-=- Properties Listing -=-=-=-
    ----------------------------------
    Property #:            793742
    Property Type:         SingleFamily
    Stories:               3
    Has Indoor Car Garage: False
    Finished Basement:     False
    Condition:             NeedsRepair
    Bedrooms:              4
    Bathrooms:             3.50
    Year Built:            1994
    Market Value:          $658,225.85
    
    Press any key to continue . . .
  16. Close the DOS window

The String: An Array of Characters

In different programs so far, when we needed a string object, we would declare a variable of type String. To support strings, the .NET Framework provides the String class. This class is defined in the C# language as the string data type. Here is an example of declaring, initializing, and using a string object:

using System;

class Exercise
{
    static int Main(string[] args)
    {
        string gender = "Female";
      
        Console.WriteLine("Gender:    {0}\n", gender);
        
        return 0;
    }
}

This would produce:

Gender:    Female

Press any key to continue . . .

From what we have studied about arrays, if you observe a value such as "Female", you may see that it primarily resembles a collection of characters. A string is a group of characters. This also means that a string is an array of characters. After declaring and initializing a string, it is considered an array of values where each character occupies a specific position. The positioned are numbered so that the most left character of the string occupies index 0; the second character is at index 1, and so on.

To support this idea of an array of characters, the String class is equipped with an indexed property named Chars. This is also how you can retrieve the character at a specific index in the string, using the [] operator of arrays. Here is an example:

using System;

class Exercise
{
    static int Main(string[] args)
    {
        string gender = "Female";
        char   gdr = gender[2];
      
        Console.WriteLine("Gender:    {0}", gender);
        Console.WriteLine("Character: {0}", gdr);
        
        Console.WriteLine();
        return 0;
    }
}

This would produce:

Gender:    Female
Character: m

Press any key to continue . . .

Once (and because) a string is considered a collection of items, you can use the foreach operator to access each member of the collection. Here is an example:

using System;

class Exercise
{
    static int Main(string[] args)
    {
        string gender = "Female";
      
        Console.WriteLine("Gender: {0}", gender);

        Console.WriteLine("\nIndividual Characters");
        foreach(char c in gender)
            Console.WriteLine("Character: {0}", c);
        return 0;
    }
}

This would produce:

Gender: Female

Individual Characters
Character: F
Character: e
Character: m
Character: a
Character: l
Character: e
Press any key to continue . . .

Converting Characters to the Opposite Case

The English language uses two character representations: lowercase and uppercase. The characters in lowercase are: a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, and z. The equivalent characters in uppercase are represented as A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, and Z. Characters used for counting are called numeric characters; each one of them is called a digit. They are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. There are other characters used to represent things in computer applications, mathematics, and others. Some of these characters, also called symbols are ~ , ! @ # $ % ^ & * ( ) _ + { } ` | = [ ] \ : " ; ' < > ? , . / These characters are used for various reasons and under different circumstances. For example, some of them are used as operators in mathematics or in computer programming. Regardless of whether a character is easily identifiable or not, all these symbols are character types and can be declared using the char data type followed by a name.

An alphabetic character, for any reason judged necessary, can be converted from one case to another. The other characters, non-alphabetic symbols, and the numbers, do not have a case and therefore cannot be converted in cases.

To convert a string from lowercase to uppercase, you can call use the ToUpper() method of the String class. It is overloaded with two versions. One of the versions of this method uses the following syntax:

public string ToUpper()

This method takes no argument. This method considers each character of the string that called it. If the character is already in uppercase, it would not change. If the character is a lowercase alphabetic character, it would be converted to uppercase. If the character is not an alphabetic character, it would be kept “as-is”. Here is an example:

using System;

class Program
{
    static int Main()
    {
        string strFullName   = "Alexander Patrick Katts";
        string strConversion = strFullName.ToUpper();

        Console.WriteLine("Full Name: " + strFullName);
        Console.WriteLine("Full Name: " + strConversion);

        return 0;
    }
}

This would produce:

Full Name: Alexander Patrick Katts
Full Name: ALEXANDER PATRICK KATTS
Press any key to continue . . .

To convert a string to lowercase, you can call the String.ToLower() method. Its syntax is:

public string ToLower();

This method follows the same logic as its counterpart: it scans the string that called it, visiting each character. If the character is not an alphabetic character, it would be kept “as-is”. If the character is an uppercase alphabetic character, it would be converted to lowercase. If it is in lowercase, it would not be converted.

Replacing a Character

If you have a string that contains a wrong character, you can either delete that character or replace it with another character of your choice. To support this operation, the String class is equipped with the Replace() method that is overloaded with two versions. One of the versions of the String.Replace() method uses the following syntax:

public string Replace(char oldChar, char newChar);

The first argument of this method is used to identify the sought character. If and everywhere that character is found in the string, it would be replaced by the character passed as the second argument. Here is an example that received a telephone number from the user and it stripped that phone number with various things to end up with only the digits:

using System;

class Program
{
    static int Main(string[] args)
    {
        string PhoneNumber;

        Console.Write("Enter Phone Number: ");
        PhoneNumber = Console.ReadLine();

        // Get a telephone number from  the user
        Console.WriteLine("\nPhone Number: " + PhoneNumber);

        // Remove the spaces
        PhoneNumber = PhoneNumber.Replace(" ", "");
        Console.WriteLine("\nPhone Number: " + PhoneNumber);

        // Remove the left parenthesis, if any
        PhoneNumber = PhoneNumber.Replace("(", "");
        // Remove the right parenthesis, if any
        PhoneNumber = PhoneNumber.Replace(")", "");
        // Remove the dash, if any
        PhoneNumber = PhoneNumber.Replace("-", "");
        Console.WriteLine("\nPhone Number: " + PhoneNumber + "\n");
        return 0;
    }
}

Here is an example of running the program:

Enter Phone Number: (303) 826-4603

Phone Number: (303) 826-4603

Phone Number: (303)826-4603

Phone Number: 3038264603

Press any key to continue . . .
 

Home Copyright © 2006-2016, FunctionX, Inc. Next