Home

Strings

 

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 or the var keyword if you are also initializing the variable. To initialize the variable, include its value between two single-quotes. Here are examples:

using System;

public static class Exercise
{
    public static int Main(string[] args)
    {
        var Gender = 'm';
        var MoneySymbol = '$';
        var Multiplication = '*';
        var 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);

        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 RealEstate4
  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;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace RealEstate4
    {
        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 RealEstate4 -> Add -> Class...
  6. Set the Name to HouseType and press Enter
  7. To derive a class, change the file as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace RealEstate4
    {
        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 RealEstate4, 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;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace RealEstate4
    {
        public class Condominium : Property
        {
            private bool handicap;
    
            public bool HandicapAccessible
            {
                get { return handicap; }
                set { handicap = value; }
            }
        }
    }
     
  11. In the Solution Explorer, right- click RealEstate4 -> Add -> Class...
  12. Set the Name to PropertyListing and press Enter
  13. Change the file as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace RealEstate4
    {
        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;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace RealEstate4
    {
        public class Program
        {
            static void Main(string[] args)
            {
                PropertyListing Listing = new PropertyListing();
    
                Listing.CreateListing();
                Console.WriteLine("\n");
                Listing.ShowListing();
            }
        }
    }
  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;

public class Exercise
{
    static int Main(string[] args)
    {
        var 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;

public class Exercise
{
    static int Main(string[] args)
    {
        var gender = "Female";
        var 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)
    {
        var 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;

public class Program
{
    static int Main(string[] args)
    {
        var strFullName   = "Alexander Patrick Katts";
        var 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;

public class Program
{
    static int Main(string[] args)
    {
        var 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 . . .

Working With Strings

 

The Length of a String

In many operations, you will need to know the number of characters a string consists of. To get the size of a string, The String class provides the Length member variable. Here is an example of using it:

using System;

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

        return 0;
    }
}

This would produce:

Gender: Female
Length: 6 Characters

Press any key to continue . . .

In the same way, you can access the Length property when processing the individual characters of a string. Here is an example:

using System;

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

        Console.WriteLine("\nIndividual Characters");
        for (int c = 0; c < gender.Length; c++)
            Console.WriteLine("Index[{0}]: {1}", c, gender[c]);

        return 0;
    }
}

This would produce:

Gender: Female
Length: 6 Characters

Individual Characters
Index[0]: F
Index[1]: e
Index[2]: m
Index[3]: a
Index[4]: l
Index[5]: e
Press any key to continue . . .

Practical Learning Practical Learning: Using Characters of a String

  1. To create a new file, on the main menu, click Project -> Add New Item...
  2. In the Templates list, click Code File
  3. Set the Name to NumericExceptions and click Add
  4. Change the file as follows:
     
    using System;
    
    // This exception is used to check and validate an integer
    public class IntegerException : Exception
    {
        public IntegerException()
        {
        }
    
        public override string Message
        {
            get
            {
                return "The value you entered is not a valid integer";
            }
        }
    }
    
    // This exception can be used to check and/or validate a decimal number
    public class FloatingPointException : Exception
    {
        public FloatingPointException()
        {
        }
    
        public override string Message
        {
            get
            {
                return "The value you entered is not a valid decimal number";
            }
        }
    }
  5. Access the PropertyListing.cs file and change it as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace RealEstate4
    {
        public enum PropertyType
        {
            Unknown,
            SingleFamily,
            Townhouse,
            Condominium
        }
    
        public class PropertyListing
        {
            . . . No Change
    
            public void CreateListing()
            {
                . . . No Change
    
                try
                {
                    Console.Write("How many bathrooms? ");
                    string strBathrooms = Console.ReadLine();
                    for (int c = 0; c < strBathrooms.Length; c++)
                    {
                        if ((strBathrooms[c] != '0') &&
                            (strBathrooms[c] != '1') &&
                            (strBathrooms[c] != '2') &&
                            (strBathrooms[c] != '3') &&
                            (strBathrooms[c] != '4') &&
                            (strBathrooms[c] != '5') &&
                            (strBathrooms[c] != '6') &&
                            (strBathrooms[c] != '7') &&
                            (strBathrooms[c] != '8') &&
                            (strBathrooms[c] != '9') &&
                            (strBathrooms[c] != '.'))
                            throw new FloatingPointException();
                    }
                    ListProperty.Bathrooms = float.Parse(strBathrooms);
                }
                catch (FloatingPointException ex)
                {
                    Console.WriteLine(ex.Message);
                }
                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 " +
    				  "been built in that year");
                }
                catch (Exception)
                {
                    Console.WriteLine("The application is " +
    				  "experiencing a problem");
                }
    
                try
                {
                    Console.Write("Property Value:     ");
                    string strValue = Console.ReadLine();
                    for (int c = 0; c < strValue.Length; c++)
                    {
                        if ((strValue[c] != '0') &&
                            (strValue[c] != '1') &&
                            (strValue[c] != '2') &&
                            (strValue[c] != '3') &&
                            (strValue[c] != '4') &&
                            (strValue[c] != '5') &&
                            (strValue[c] != '6') &&
                            (strValue[c] != '7') &&
                            (strValue[c] != '8') &&
                            (strValue[c] != '9') &&
                            (strValue[c] != '.'))
                            throw new FloatingPointException();
                    }
                    ListProperty.Value = decimal.Parse(strValue);
                }
                catch (FloatingPointException ex)
                {
                    Console.WriteLine(ex.Message);
                }
                catch (Exception)
                {
                    Console.WriteLine("This is where the application " +
    				  "draws the line: it stops!");
                }
            }
    
            . . . No Change
        }
    }
  6. 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 #: 284866
    
    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): m
    Is the basement finished(y/n): u
    
    How many bedrooms?  4
    How many bathrooms? 3.50
    Year built:         1995
    Property Value:     735000
    
    
    ==================================
     =//=//= Altair Realty =//=//=
    -=-=-=- Properties Listing -=-=-=-
    ----------------------------------
    Property #:            284866
    Property Type:         SingleFamily
    Stories:               3
    Has Indoor Car Garage: False
    Finished Basement:     False
    Condition:             NeedsRepair
    Bedrooms:              4
    Bathrooms:             3.50
    Year Built:            1995
    Market Value:          $735,000.00
    Press any key to continue . . .
  7. Close the DOS window
  8. Execute the application again. 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 #: 284866
    
    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): N
    Is the basement finished(y/n): Y
    
    How many bedrooms?  4
    How many bathrooms? 3.r0
    The value you entered is not a valid decimal number
    Year built:         1995
    Property Value:     7.35e5
    The value you entered is not a valid decimal number
    
    
    ==================================
     =//=//= Altair Realty =//=//=
    -=-=-=- Properties Listing -=-=-=-
    ----------------------------------
    Property #:            284866
    Property Type:         SingleFamily
    Stories:               3
    Has Indoor Car Garage: False
    Finished Basement:     True
    Condition:             NeedsRepair
    Bedrooms:              4
    Bathrooms:             0.00
    Year Built:            1995
    Market Value:          $0.00
    Press any key to continue . . .
  9. Close the DOS window

Replacing a Sub-String

Inside of a string, if you have a combination of consecutive character you don't want to keep, you can either remove that sub-string or replace it with an new combination of consecutive characters of your choice. To support this operation, the String class provides anopther version of the the Replace() method whose syntax is:

public string Replace(string oldStr, string newStr);

The oldStr argument is the sub-string to look for in the string. Whenever that sub-string is found in the string, it is replaced by the newStr argument.

Formatting a String

Formatting a string consists of specifying how it would be presented as an object. To support this operation, the String class is equipped with a static method named Format. The String.Format() method is overloaded in various versions; the syntax of the simplest is:

public static string Format(string format, Object arg0);

This method takes two arguments and it follows the same techniques we reviewed in Lesson 5 for data formatting. This means that the first argument can contain one or a combination of {} operators that include incrementing numbers. The second argument contains one or a combination of values that would be added to the {} operators of the first argument.

Here is an example:

using System;

public class Exercise
{
    static int Main(string[] args)
    {
        var wage = 22.45;
        var strDisplay = string.Format("Hourly Salary: {0}", wage);

        Console.WriteLine(strDisplay);

        return 0;
    }
}

This would produce:

Side: 25.85
Hourly Salary: 22.45
Press any key to continue . . .

Copying a String

After declaring and initializing one String variable, you can assign it to another String variable using the assignment operator. Here is an example:

using System;

public class Exercise
{
    static int Main(string[] args)
    {
        var strPerson   = "Charles Stanley";
        var strSomebody = strPerson;

        Console.WriteLine("Full Name: " + strPerson);
        Console.WriteLine("Full Name: " + strSomebody);

        return 0;
    }
}

This would produce:

Full Name: Charles Stanley
Full Name: Charles Stanley
Press any key to continue . . .

Assigning one variable to another is referred to as copying it. To formally support this operator, the String class is equipped with the Copy() method. Its syntax is:

public static string Copy(string str);

This method takes as argument an existing String object and copies it, producing a new string. Here is an example:

using System;

class Program
{
    static int Main(string[] args)
    {
        var strPerson   = "Charles Stanley";
        var strSomebody = string.Copy(strPerson);

        Console.WriteLine("Full Name: " + strPerson);
        Console.WriteLine("Full Name: " + strSomebody);

        return 0;
    }
}

The string.Copy() method is used to copy all characters of one string into another another. If you want to copy only a few characters, use the string.CopyTo() method. Its syntax is:

public void CopyTo(int sourceIndex, 
		   char[] destination, 
		   int destinationIndex, 
	    	   int count);

Operations on Strings

 

String Concatenation

One of the routine operations you can perform on two strings consists of adding one to another, that is, putting one string to the right of another string, to produce a new string made of both. There are two techniques you can use.

To add one string to another, you can use the addition operator as done in arithmetic. Here is an example:

using System;

public class Exercise
{
    static int Main(string[] args)
    {
        var strNeed = "Needs";
        var strRepair = "Repair";
        var strAddition = strNeed + strRepair;

        Console.WriteLine(strAddition);

        return 0;
    }
}

This would produce:

NeedsRepair
Press any key to continue . . .

In the same way, you can add as many strings as necessary using +. Here is an example:

using System;

public class Exercise
{
    static int Main(string[] args)
    {
        var strFirstName  = "Alexander";
        var strMiddleName = "Patrick";
        var strLastName   = "Katts";
        var strFullName   = strFirstName + " " + 
                            strMiddleName + " " + 
                            strLastName;

        Console.WriteLine("First Name:  " + strFirstName);
        Console.WriteLine("Middle Name: " + strMiddleName);
        Console.WriteLine("Last Name:   " + strLastName);
        Console.WriteLine("Full Name:   " + strFullName + "\n");

        return 0;
    }
}

This would produce:

First Name:  Alexander
Middle Name: Patrick
Last Name:   Katts
Full Name:   Alexander Patrick Katts

Press any key to continue . . .

Besides the addition operator, to formally support string concatenation, the String class provides the Concat() method that is overloaded in various versions. One of the versions of this method takes two String arguments. Its syntax is:

public static string Concat(string str1, string str2);

This versions takes two strings that should be concatenated. The method returns a new string as the first added to the second. Two imitations of this version use the following versions:

public static string Concat(string str0, 
			    string str1, 
			    string str2);
public static string Concat(string str0,
			    string str1,
			    string str2, 
			    string str3);

In each case, the method takes the number of strings and adds them.

Strings Comparisons

 

Introduction

String comparison consists of examining the characters of two strings with a character of one string compared to a character of the other string with both characters at the same positions. To support this operation, the String class is equipped with the Compare() method that is overloaded in many versions. One of the versions uses the following syntax:

public static int Compare(string String1, string  String2);

This method is declared static and it takes two arguments. When it starts, the first character of the first argument is compared to the first character of the second string. Alphabetically, if the first character of the first string has a lower alphabetical index than the first character of the second, this method returns a negative value. If the first character of the first string has a higher alphabetical index than the first character of the second, this method returns a positive value. If the first characters of both strings are the same, the method continues with the second character of each string. If both strings have the exact same characters, the method returns 0. This can be resumed as follows. The method returns

  • A negative value if string1 is less than string2
  • 0 if string1 and string2 are equal
  • A positive value if string1 is greater than string2

Here is an example:

using System;

public class Exercise
{
    static int Main(string[] args)
    {
        var FirstName1 = "Andy";
        var LastName1 = "Stanley";
        var FirstName2 = "Charles";
        var LastName2 = "Stanley";

        var Value1 = string.Compare(FirstName1, FirstName2);
        var Value2 = string.Compare(FirstName2, FirstName1);
        var Value3 = string.Compare(LastName1, LastName2);

        Console.WriteLine("The result of comparing " + 
                          FirstName1 + " and " + FirstName2 +
                          " is\t" + Value1.ToString());
        Console.WriteLine("The result of comparing " + 
                          FirstName2 + " and " + FirstName1 +
                          " is\t" + Value2.ToString());
        Console.WriteLine("The result of comparing " +
                          LastName1 + " and " + LastName2 + 
                          " is\t" + Value3.ToString() + "\n");

        return 0;
    }
}

This would produce:

The result of comparing Andy and Charles is     -1
The result of comparing Charles and Andy is     1
The result of comparing Stanley and Stanley is  0

Press any key to continue...

When using this version of the string.Compare() method, the case (upper or lower) of each character is considered. If you don't want to consider this factor, the String class proposes another version of the method. Its syntax is:

public static int Compare(string String1, string String2, bool ignoreCase);

The third argument allows you to ignore the case of the characters when performing the comparison.

String Equality

In the previous section, we saw that the indexed-equivalent characters of two strings can be compared to know whether one is lower or higher than the other's. If you are only interested to know whether two strings are equivalent, you can call the Equals() method of the String class. It is overloaded with various versions. Two versions use the following syntaxes:

public override bool Equals(object obj);
public bool Equals(string value);

When calling one of these versions, use an Object object or a String variable that calls it. The method takes one argument. The variable that calls the method is compared to the value passed as argument. If both values are the exact same, the method returns true. The comparison is performed considering the case of each character. If you don't want to consider the case, use the following version of the method:

public bool Equals(string value, StringComparison comparisonType);

An alternative to the second syntax is to use a static version of this method whose syntax is:

public static bool Equals(string a, string b);

This method takes two String arguments and compares them. If they are the same, the method returns true. This method considers the cases of the characters. If you don't want this factor taken into consideration, use the following version of the method:

public static bool Equals(string a, string b, StringComparison comparisonType);

Working With Sub-Strings

 

Introduction

A sub-string is a section or part of a string. To create a sub-string, you first need a string and can retrieve one or more values from it. To support this, the String class is equipped with the Substring() method that is overloaded in two versions. The syntax of one is:

public string Substring(int startIndex);

The integer argument specifies the position of the first character from the variable that called the method. The return value is a new String that is made of the characters from startIndex to the end of the string.

Sub-String Creation

Probably the most consistent way to create a string is to control the beginning and end retrieved from the original string. To support this, the String class is equipped with another version of the Substring() method. Its syntax is:

public string  Substring(int startIndex, int length);

The first argument specifies the index of the character to start from the String variable that calls this method. The second argument specifies the length of the string.

 

 

Previous Copyright © 2008-2016, FunctionX, Inc. Next