Home

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;

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

class Exercise
{
    static int Main(string[] args)
    {
        string 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;
    
    class IntegerException : Exception
    {
        public IntegerException()
        {
        }
    
        public override string Message
        {
            get
            {
                return "The value you entered is not a valid integer";
            }
        }
    }
    
    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;
    
    namespace RealEstate6
    {
        public enum PropertyType
        {
            Unknown,
            SingleFamily,
            Townhouse,
            Condominium
        }
    
        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 Program
{
    static int Main(string[] args)
    {
        double wage = 22.45;
        string 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;

class Program
{
    static int Main()
    {
        string strPerson   = "Charles Stanley";
        string 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 strPerson   = "Charles Stanley";
        string 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);

 

 

 

Previous Copyright © 2006 FunctionX, Inc. Next