Home

Operations on Strings

Fundamental Operations on Strings

The Mutability and Immutability of a String

An object is said to be mutable if it can change at will. This means that when something, anything, such as an external action, occurs, the nature (such as structure and/or appearance) of the object changes tremendously.

An object is immutable, or not mutable, if its nature cannot change. The only way to get a similar object is only to create a new object that looks, or appears, like the first one.

The String class is one of the largest types in the .NET Framework. It includes many methods to perform all types of operations neccessary on a string. The string type is immutable. This means that every time you perform an operation that modifies a string object, you get a brand new string, not a copy, not a duplicate. If you manipulate many strings in your code, you may think that you should be concerned with the computer memory. Don't get concerned with memory. The C# compiler takes care of all memory concerns behind the scenes.

Practical LearningPractical Learning: Introducing Strings Operations

  1. Start Microsoft Visual Studio and create a Windows Forms application named AccountValidation3
  2. Design the form as follows:

    Fundamental Operations on Strings

    Control (Name) Text
    GroupBox   Account Setup
    Label   First Name:
    TextBox txtFirstName  
    Label   Middle Name:
    TextBox txtMiddleName  
    Label   Last Name:
    TextBox txtLastName  
    Label   ________________
    Label   New Password:
    TextBox txtNewPassword  
    Label   Confirm Password:
    TextBox txtConfirmPassword  
    GroupBox   Account Summary
    Label   Full Name:
    TextBox txtFullName  
    Label   Username:
    TextBox txtUsername  
    GroupBox   Password Summary
    Label   Number of Characters:
    TextBox txtCharacters  
    Label   Lowercase Letters:
    TextBox txtLowercaseLetters  
    Label   Uppercase Letters:
    TextBox txtUppercaseLetters  
    Label   Digits:
    TextBox txtDigits  
    Label   Symbols:
    TextBox txtSymbols  
  3. On the form, click the First Name text box
  4. In the Properties window, click the Events button Events
  5. Double-click Leave
  6. Return to the form and click the Middle Name text box
  7. In the Events section of the Properties window, double-click Leave
  8. Return to the form and click the Last Name text box
  9. In the Events section of the Properties window, double-click Leave

Adding Strings

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;
using System.Windows.Forms;

namespace Exercise01
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnStrings_Click(object sender, EventArgs e)
        {
            string quote = "Never let your head hang down. Never give up and sit down and grieve. Find another way. And don't pray when it rains if you don't pray when the sun shines.";
            string author = "President Nixon";
            string quotation = quote + author;

            MessageBox.Show(quotation, "Quotation");
        }
    }
}

This would produce:

Moving a Window

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

using System;
using System.Windows.Forms;

namespace Exercise01
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnStrings_Click(object sender, EventArgs e)
        {
            string quote = "Never let your head hang down. Never give up and sit down and grieve. Find another way. And don't pray when it rains if you don't pray when the sun shines.";
            string firstName = "Richard";
            string middleInitial = "M";
            string lastName = "Nixon";
            string quotation = quote + " - " + firstName + " " + middleInitial + ". " + lastName;

            MessageBox.Show(quotation, "Quotation");
        }
    }
}

This would produce:

Moving a Window

Concatenating Some Strings

Besides the addition operator, to formally support string concatenation, the string data type 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 is 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 a group of strings and adds them.

Practical LearningPractical Learning: Concatenating Some Strings

  1. Change the document as follows:
    using System;
    using System.Windows.Forms;
    
    namespace AccountValidation3
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            void CreateUsername()
            {
                string strFirstName  = txtFirstName.Text;
                string strMiddleName = txtMiddleName.Text;
                string strLastName   = txtLastName.Text;
    
                // If the text boxes of the first, middle, and last names are empty, leave the username and the full name text boxes empty.
                if( (string.IsNullOrEmpty(txtFirstName.Text)) && (string.IsNullOrEmpty(txtMiddleName.Text)) && (string.IsNullOrEmpty(txtLastName.Text)))
                {
                    txtUsername.Text = "";
                    txtFullName.Text = "";
                    return;
                }
    
                /* Create a full name as a combination of the first, middle, and last names. 
                 * Do this depending on the available name(s). */
                if(string.IsNullOrEmpty(txtLastName.Text))
                    txtFullName.Text = strFirstName;
                else
                {
                    if (strMiddleName == "")
                        txtFullName.Text = string.Concat(strLastName, ", ", strFirstName);
                    else
                        txtFullName.Text = string.Concat(strLastName, ", ", strFirstName, " ", strMiddleName);
                }
            }
    
            private void txtFirstName_Leave(object sender, EventArgs e)
            {
                CreateUsername();
            }
    
            private void txtMiddleName_Leave(object sender, EventArgs e)
            {
                CreateUsername();
            }
    
            private void txtLastName_Leave(object sender, EventArgs e)
            {
                CreateUsername();
            }
        }
    }
  2. To execute the project, on the main menu, click Debug -> Start Without Debugging:

    Concatenating Some Strings

  3. In the First Name text box, type a name such as Jennifer and press Tab:

    Concatenating Some Strings

  4. Click the Last Name text box
  5. Type a name such as Garrison and press Tab:

    Integrally Comparing Strings

  6. Click the Middle Name text box
  7. Type a name such as Christine and press Tab:

    Integrally Comparing Strings

  8. Close the form and return to your programming environment
  9. Start a new Console App (.NET Framework) application named GeorgetownDryCleaningServices7
  10. Change the Program.cs document as follows:
    using static System.Console;
    
    namespace GeorgetownDryCleaningServices7
    {
        public class Program
        {
            public static int Main(string[] args)
            {
            	  // Price of items
                const double PriceOneShirt = 1.35;
                const double PriceAPairOfPants = 2.95;
                const double PriceOneDress = 4.55;
                const double taxRate = 0.0575;  // 5.75%
    
                // Customer personal information
                string customerName, homePhone;
                // Unsigned numbers to represent cleaning items
                uint numberOfShirts, numberOfPants, numberOfDresses;
                // Each of these sub totals will be used for cleaning items
                double subTotalShirts, subTotalPants, subTotalDresses;
                // Values used to process an order
                double totalOrder, taxAmount, salesTotal;
                double amountTended, moneyChange;
    
                Title = "Georgetown Dry Cleaning Services";
                WriteLine("-/- Georgetown Dry Cleaning Services -/-");
    
                // Request customer information from the user
                Write("Enter Customer Name:    ");
                customerName = ReadLine();
                Write("Enter Customer Phone:   ");
                homePhone = ReadLine();
    
                // Request the quantity of each category of items
                Write("Number of Shirts:       ");
                string strShirts = ReadLine();
                numberOfShirts = uint.Parse(strShirts);
    
                Write("Number of Pants:        ");
                string strPants = ReadLine();
                numberOfPants = uint.Parse(strPants);
    
                Write("Number of Dresses:      ");
                string strDresses = ReadLine();
                numberOfDresses = uint.Parse(strDresses);
    
                // Perform the necessary calculations
                subTotalShirts = numberOfShirts * PriceOneShirt;
                subTotalPants = numberOfPants * PriceAPairOfPants;
                subTotalDresses = numberOfDresses * PriceOneDress;
                // Calculate the "temporary" total of the order
                totalOrder = subTotalShirts + subTotalPants + subTotalDresses;
    
                // Calculate the tax amount using a constant rate
                taxAmount = totalOrder * taxRate;
                // Add the tax amount to the total order
                salesTotal = totalOrder + taxAmount;
    
                WriteLine();
    
                // Communicate the total to the user...
                WriteLine("The Total order is: ");
                WriteLine(salesTotal.ToString("F"));
                // and request money for the order
                Write("Amount Tended?          ");
                amountTended = double.Parse(ReadLine());
    
                // Calculate the difference owed to the customer
                // or that the customer still owes to the store
                moneyChange = amountTended - salesTotal;
    
                Clear();
    
                // Display the receipt
                WriteLine("====================================");
                WriteLine("-/- Georgetown Dry Cleaning Services -/-");
                WriteLine("====================================");
                WriteLine("Customer:   {0}", customerName);
                WriteLine("Home Phone: {0}", homePhone);
                WriteLine("------------------------------------");
                WriteLine("Item Type  Qty Unit/Price Sub-Total");
                WriteLine("------------------------------------");
                WriteLine("Shirts      {0}     {1}     {2}",
                          numberOfShirts, PriceOneShirt.ToString("F"), subTotalShirts.ToString("C"));
                WriteLine("Pants       {0}     {1}     {2}",
                          numberOfPants, PriceAPairOfPants.ToString("F"), subTotalPants.ToString("C"));
                WriteLine("Dresses     {0}     {1}     {2}",
                          numberOfDresses, PriceOneDress.ToString("F"), subTotalDresses.ToString("C"));
                WriteLine("------------------------------------");
                WriteLine("Total Order:     {0}", totalOrder.ToString("C"));
                WriteLine("Tax Rate:        {0}", taxRate.ToString("P"));
                WriteLine("Tax Amount:      {0}", taxAmount.ToString("C"));
                WriteLine("Net Price:       {0}", salesTotal.ToString("C"));
                WriteLine("------------------------------------");
                WriteLine("Amount Tended:   {0}", amountTended.ToString("C"));
                WriteLine("Difference:      {0}", moneyChange.ToString("C"));
                WriteLine("====================================\n");
    
                return 0;
            }
        }
    }
  11. To execute the project to test it, on the main menu of Microsoft Visual Studio, click Debug -> Start Without Debugging
  12. When requested, enter some values as follows and press Enter each time:
    Enter Customer Name:   Arthur Brown
    Enter Customer Phone: (240) 158-9627
    Number of Shirts:     8
    Number of Pants:      6
    Number of Dresses:    3
    Amount Tended:	    50

    Formatting a String

    Formatting a String

  13. Press Enter to close the DOS window and return to your programming environment

Compound Concatenation

To add a character or a string to an existing string, use the += operator. When the operator has been used, the string is made of the characters it previously had plus the new character(s). Here is an example:

using System;
using System.Windows.Forms;

namespace Exercise01
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnStrings_Click(object sender, EventArgs e)
        {
            string quote = "Nihilism is a natural consequence of a culture (or civilization) ruled and regulated by categories that mask manipulation, mastery and domination of peoples and nature.";
            quote += " - ";
            quote += "Cornel";
            quote += " ";
            quote += "West";

            MessageBox.Show(quote, "Quotation");
        }
    }
}

This would produce:

Compound Concatenation

Formatting a String

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

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

This method takes two arguments. 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.

If you need two placeholders for values, use the following version of the method:

public static string Format(string format, object arg0, object arg1)

The first argument can contain a string plus {0} and {1} anywhere in the string (but {0} must come before {1}). The second argument will be used in place of {0} in the first argument, and the third argument will be used in place the {1} placeholders.

If you need three placeholders for values, use the following version of the method:

public static string Format(string format, object arg0, object arg1, object arg2)

The first argument can contain a string plus {0}, {1}, and {2} anywhere in the string (but the {0}, {1}, and {2} must appear in that order). The second argument will be used in place of {0} in the first argument, the third argument will be used in place the {1} placeholder, and the fourth argument will be used in place of {2}.

If you need more than three placeholders for values, use the following version of the method:

public static string Format(string format, params object[] args)

The first argument can contain one or a combination of {number} placeholders. The second argument is one or a combination of values that would be orderly added to the {number} placeholders of the first argument.

Practical LearningPractical Learning: Formatting Some Strings

  1. Change the Program.cs document as follows:
    using static System.Console;
    
    namespace GeorgetownDryCleaningServices7
    {
        public class Program
        {
            public static int Main(string[] args)
            {
                // Price of items
                const double PriceOneShirt = 1.35;
                const double PriceAPairOfPants = 2.95;
                const double PriceOneDress = 4.55;
                const double taxRate = 0.0575;  // 5.75%
    
                // Customer personal infoirmation
                string customerName, homePhone;
                // Unsigned numbers to represent cleaning items
                uint numberOfShirts, numberOfPants, numberOfDresses;
                // Each of these sub totals will be used for cleaning items
                double subTotalShirts, subTotalPants, subTotalDresses;
                // Values used to process an order
                double totalOrder, taxAmount, salesTotal;
                double amountTended, moneyChange;
    
                Title = "Georgetown Dry Cleaning Services";
                WriteLine("-/- Georgetown Dry Cleaning Services -/-");
    
                // Request customer information from the user
                Write("Enter Customer Name:  ");
                customerName = ReadLine();
                Write("Enter Customer Phone: ");
                homePhone = ReadLine();
    
                // Request the quantity of each category of items
                Write("Number of Shirts:     ");
                string strShirts = ReadLine();
                numberOfShirts = uint.Parse(strShirts);
    
                Write("Number of Pants:      ");
                string strPants = ReadLine();
                numberOfPants = uint.Parse(strPants);
    
                Write("Number of Dresses:    ");
                string strDresses = ReadLine();
                numberOfDresses = uint.Parse(strDresses);
    
                // Perform the necessary calculations
                subTotalShirts = numberOfShirts * PriceOneShirt;
                subTotalPants = numberOfPants * PriceAPairOfPants;
                subTotalDresses = numberOfDresses * PriceOneDress;
                // Calculate the "temporary" total of the order
                totalOrder = subTotalShirts + subTotalPants + subTotalDresses;
    
                // Calculate the tax amount using a constant rate
                taxAmount = totalOrder * taxRate;
                // Add the tax amount to the total order
                salesTotal = totalOrder + taxAmount;
    
                WriteLine();
    
                // Communicate the total to the user...
                Write("The Total order is:   ");
                WriteLine(salesTotal.ToString("F"));
                // and request money for the order
                Write("Amount Tended?        ");
                amountTended = double.Parse(ReadLine());
    
                // Calculate the difference owed to the customer
                // or that the customer still owes to the store
                moneyChange = amountTended - salesTotal;
    
                Clear();
    
                // Display the receipt
                string strCustomerDisplay = string.Format("Customer:   {0}", customerName);
                string phoneDisplay = string.Format("Home Phone: {0}", homePhone);
                string shirtDisplay = string.Format("Shirts      {0}     {1}     {2}",
                                      numberOfShirts, PriceOneShirt.ToString("F"), subTotalShirts.ToString("C"));
    
                WriteLine("====================================");
                WriteLine("-/- Georgetown Dry Cleaning Services -/-");
                WriteLine("====================================");
                WriteLine(strCustomerDisplay);
                WriteLine(phoneDisplay);
                WriteLine("------------------------------------");
                WriteLine("Item Type  Qty Unit/Price Sub-Total");
                WriteLine("------------------------------------");
                WriteLine(shirtDisplay);
                WriteLine(string.Format("Pants       {0}     {1}     {2}",
                          numberOfPants, PriceAPairOfPants.ToString("F"), subTotalPants.ToString("C")));
                WriteLine(string.Format("Dresses     {0}     {1}     {2}",
                          numberOfDresses, PriceOneDress.ToString("F"), subTotalDresses.ToString("C")));
                WriteLine("------------------------------------");
                WriteLine(string.Format("Total Order:     {0}", totalOrder.ToString("C")));
                WriteLine(string.Format("Tax Rate:        {0}", taxRate.ToString("P")));
                WriteLine(string.Format("Tax Amount:      {0}", taxAmount.ToString("C")));
                WriteLine(string.Format("Net Price:       {0}", salesTotal.ToString("C")));
                WriteLine("------------------------------------");
                WriteLine(string.Format("Amount Tended:   {0}", amountTended.ToString("C")));
                WriteLine(string.Format("Difference:      {0}", moneyChange.ToString("C")));
                WriteLine("====================================\n");
    
                return 0;
            }
        }
    }
  2. To execute the project, on the main menu, click Debug -> Start Without Debugging
  3. When requested, enter some values as follows and press Enter each time:
    Enter Customer Name:  Arthur Brown
    Enter Customer Phone: (240) 158-9627
    Number of Shirts:     8
    Number of Pants:      6
    Number of Dresses:    3
    Amount Tended:	    50

    Formatting a String

    Formatting a String

  4. Press Enter to close the DOS window and return to your programming environment
  5. To access a previous project, on the main menu, click File -> Recent Projects and Solutions -> AccountValidation3

String Interpolation

String interpolation consists of starting string formatting with the $ symbol followed by the normal double-quotes that contains one or a combination of {}. Between the curly brackets, type the name of the variable whose values would be displayed. Here are examples:

using System;
using System.Windows.Forms;

namespace Exercise01
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnStrings_Click(object sender, EventArgs e)
        {
            var employeeNumber = "359-486";
            string firstName = "Claire";
            dynamic lastName = "Simmons";

            String identification = $"{employeeNumber}: {lastName}, {firstName}";
            MessageBox.Show(identification, "Employee Identification");
        }
    }
}

This would produce:

Compound Concatenation

Sub-Strings

Introduction

A sub-string is a section or part of a string. Obviously, to get a sub-string, you first need an existing string.

Fundamentals of Creating a Sub-String

There are various ways you can create a sub-string from an existing string. As one way, you can retrieve one or more characters from an existing string. To support this, the String class is equipped with a method named Substring() that is overloaded with two versions. The syntax of one version 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.

Another technique to create a sub-string consists of extracting it from the beginning of an 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.

Practical LearningPractical Learning: Creating Sub-Strings

  1. Change the code as follows:
    using System;
    using System.Windows.Forms;
    
    namespace AccountValidation3
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            void CreateUsername()
            {
                string strFirstName  = txtFirstName.Text;
                string strMiddleName = txtMiddleName.Text;
                string strLastName   = txtLastName.Text;
    
                // If the text boxes of the first, middle, and last names are empty, leave the username and the full name text boxes empty.
                if( (string.IsNullOrEmpty(txtFirstName.Text)) && (string.IsNullOrEmpty(txtMiddleName.Text)) && (string.IsNullOrEmpty(txtLastName.Text)))
                {
                    txtUsername.Text = "";
                    txtFullName.Text = "";
                    return;
                }
    
                /* Create a full name as a combination of the first, middle, and last names. 
                 * Do this depending on the available name(s). */
                if(string.IsNullOrEmpty(txtLastName.Text))
                    txtFullName.Text = strFirstName;
                else
                {
                    if (strMiddleName == "")
                        txtFullName.Text = string.Concat(strLastName, ", ", strFirstName);
                    else
                        txtFullName.Text = string.Concat(strLastName, ", ", strFirstName, " ", strMiddleName);
                }
    
                // If the user provides only the first and last names (no middle name, ...
                if (string.IsNullOrEmpty(txtMiddleName.Text))
                {
                    /* ... create a user name that uses the first letter of 
                     * the first name + the whole last name. Convert the username to lower case. */
                    txtUsername.Text = $"{strFirstName.Substring(0, 1)}{strLastName}".ToLower();
                }
                else
                {
                    /* If the user provides the first, the middle, and the last names, 
                     * create a user name as a combination of the first letter of the 
                     * first name, the first letter of the middle name, and the last name. 
                     * Convert the username to lower case. */
                    txtUsername.Text = $"{strFirstName.Substring(0, 1)}{strMiddleName.Substring(0, 1)}{strLastName}".ToLower();
                }
            }
    
            private void txtFirstName_Leave(object sender, EventArgs e)
            {
                CreateUsername();
            }
    
            private void txtMiddleName_Leave(object sender, EventArgs e)
            {
                CreateUsername();
            }
    
            private void txtLastName_Leave(object sender, EventArgs e)
            {
                CreateUsername();
            }
        }
    }
  2. To execute the project, on the main menu, click Debug -> Start Without Debugging
  3. In the First Name text box, type a name such as Jennifer and press Tab twice:

    Concatenating Some Strings

  4. In the Last Name text box, type a name such as Garrison and press Tab:

    Integrally Comparing Strings

  5. Click the Middle Name text box
  6. Type a name such as Christine and press Tab:

    Integrally Comparing Strings

  7. Close the form and return to your programming environment

Looking for a Character or a Sub-String in a String

To assist you with looking for a character or a sub-string within a string, the String class provides a method named Contains. Its syntax is:

public bool Contains(string value)

Unwanted Characters and Sections in a String

Trimming a String

Trimming a string consists of removing empty spaces from it. To let you remove empty spaces from the left side of a string, the String class is equipped with a method named TrimStart. Its syntax is:

public string TrimStart(params char[] trimChars)

To let you remove empty spaces from the right side of a string, the String class provides the TrimEnd method. Its syntax is:

public string TrimEnd(params char[] trimChars)

To let you remove empty spaces from both sides of a string, the String class is equipped with a method named Trim. It is overloaded with two versions. Their syntaxes are:

public string Trim()
public string Trim(params char[] trimChars)

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 a method named Replace 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.

Replacing a Sub-String

Inside of a string, if you have a combination of consecutive characters you don't want to keep, you can either remove that sub-string or replace it with a new combination of consecutive characters of your choice. To support this operation, the String class provides a version of 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.

Duplicating a String

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:

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

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:

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

Copying To a String

The string.Copy() method is used to copy all characters of one string into another. To let you copy only a few characters, the String class is equipped with a method named CopyTo. Its syntax is:

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

Strings and Methods

Passing a String to a Function or Method

Like a normal value, a string can be passed to a function or method. When calling the function or method, you can pass a value for the argument in double-quotes or provide the name of a variable that holds the string.

Returning a String From a Function

You can create a function or method that returns a string. This is done the same way as with the other classes.

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2020, FunctionX Next