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 Console App (that supports .NET 8.0 (Long-Term Support)) named AccountValidation2
  2. From the Solution Explorer, rename Program.cs as AccountValidation.cs

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 static System.Console;

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;

WriteLine(quotation);

This would produce:

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.President Nixon

Press any key to close this window . . .

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

sing static System.Console;

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;

WriteLine(quotation);

This would produce:

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. - Richard M. Nixon

Press any key to close this 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 static System.Console;
    
    Write("First Name:  ");
    string strFirstName = ReadLine()!;
    Write("Middle Name: ");
    string strMiddleName = ReadLine()!;
    Write("Last Name:   ");
    string strLastName = ReadLine()!;
    
    if( (string.IsNullOrEmpty(strFirstName)) && 
        (string.IsNullOrEmpty(strMiddleName)) && 
        (string.IsNullOrEmpty(strLastName)) )
    {
        throw new System.Exception("Missing values from the first name, the middle name, and the last name.");
    }
    
    /* 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(strLastName))
        WriteLine("Full Name: " + strFirstName);
    else
    {
        if (strMiddleName == "")
            WriteLine("Full Name: " + string.Concat(strLastName, ", ", strFirstName));
        else
            WriteLine("Full Name: " + string.Concat(strLastName, ", ", strFirstName, " ", strMiddleName));
    }
  2. To execute the project, on the main menu, click Debug -> Start Without Debugging
  3. When requested, type the First Name as Jennifer and press Enter
  4. When the middle name is requested, type Christine and press Enter
  5. For the Last Name, type Garrison and press Enter:
    First Name:  Jennifer
    Middle Name: Christine
    Last Name:   Garrison
    Full Name: Garrison, Jennifer Christine
    
    Press any key to close this window . . .
  6. Close the window and return to your programming environment
  7. Start a new Console App (that supports .NET 8.0 (Long=Term Support)) named GeorgetownDryCleaningServices5
  8. Change the Program.cs document as follows:
    using static System.Console;
    
    // 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("====================================");
  9. To execute the project to test it, on the main menu of Microsoft Visual Studio, click Debug -> Start Without Debugging
  10. When requested, enter some values as follows and press Enter each time:
    -/- Georgetown Dry Cleaning Services -/-
    Enter Customer Name:    Arthur Brown
    Enter Customer Phone:   (240) 158-9627
    Number of Shirts:       8
    Number of Pants:        6
    Number of Dresses:      3
                      
    The Total order is:     44.57
    Amount Tended?          50

    ====================================
    -/- Georgetown Dry Cleaning Services -/-
    ====================================
    Customer:   Arthur Brown
    Home Phone: (240) 158-9627
    ------------------------------------
    Item Type  Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts      8     1.35     $10.80
    Pants       6     2.95     $17.70
    Dresses     3     4.55     $13.65
    ------------------------------------
    Total Order:     $42.15
    Tax Rate:        5.75%
    Tax Amount:      $2.42
    Net Price:       $44.57
    ------------------------------------
    Amount Tended:   $50.00
    Difference:      $5.43
    ====================================
    
    Press any key to close this window . . .
  11. 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 static System.Console;

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";

WriteLine(quote, "Quotation");

This would produce:

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. - Cornel West
.
Press any key to close this window . . .

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;
    
    // 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("====================================");
  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:
    -/- Georgetown Dry Cleaning Services -/-
    Enter Customer Name:  Arthur Brown
    Enter Customer Phone: (240) 158-9627
    Number of Shirts:     8
    Number of Pants:      6
    Number of Dresses:    3
    
    The Total order is:   44.57
    Amount Tended?        50

    ====================================
    -/- Georgetown Dry Cleaning Services -/-
    ====================================
    Customer:   Arthur Brown
    Home Phone: (240) 158-9627
    ------------------------------------
    Item Type  Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts      8     1.35     $10.80
    Pants       6     2.95     $17.70
    Dresses     3     4.55     $13.65
    ------------------------------------
    Total Order:     $42.15
    Tax Rate:        5.75%
    Tax Amount:      $2.42
    Net Price:       $44.57
    ------------------------------------
    Amount Tended:   $50.00
    Difference:      $5.43
    ====================================
    
    Press any key to close this window . . .
  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 -> AccountValidation2

String Interpolation

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

sing static System.Console;

var employeeNumber = "359-486";
string firstName = "Claire";
dynamic lastName = "Simmons";

string identification = $"{employeeNumber}: {lastName}, {firstName}";
WriteLine(identification, "Employee Identification");

This would produce:

359-486: Simmons, Claire

Press any key to close this window . . .

You can also use string interpolation to display the values of the items of a tuple. To do this, in the curly brackets ({}), access the desired member of the tuple. Here are examples:

using System;

(int emplNumber, string firstName, string lastName, double salary) employee = (284_928, "Paul-Simon", "Ndongo", 73_866);

Console.WriteLine("Employee Record");
Console.WriteLine("---------------------------------------");
Console.WriteLine($"Employee #:    {employee.emplNumber}");
Console.WriteLine($"Full Name:     {employee.Item2} {employee.lastName}");
Console.WriteLine($"Yearly Salary: {employee.Item4}");
Console.WriteLine("=======================================");

This would produce:

Employee Record
---------------------------------------
Employee #:    284928
Full Name:     Paul-Simon Ndongo
Yearly Salary: 73866
=======================================
Press any key to continue . . .

Of course, you can also use a var tuple. Here are examples:

sing static System.Console;

var staff = (emplNumber: 284928, "Paul-Simon", lastName: "Ndongo", 73866, fullTime: true);

Console.WriteLine("Employee Record");
Console.WriteLine("---------------------------------------");
Console.WriteLine($"Employee #:         {staff.emplNumber}");
Console.WriteLine($"Full Name:          {staff.Item2} {staff.lastName}");
Console.WriteLine($"Yearly Salary:      {staff.Item4}");
Console.WriteLine($"Employed Full-Time: {staff.Item5}");
Console.WriteLine("=======================================");

This would produce:

Employee Record
---------------------------------------
Employee #:         284928
Full Name:          Paul-Simon Ndongo
Yearly Salary:      73866
Employed Full-Time: True
=======================================
Press any key to continue . . .

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 static System.Console;
    
    Write("First Name:  ");
    string strFirstName = ReadLine()!;
    Write("Middle Name: ");
    string strMiddleName = ReadLine()!;
    Write("Last Name:   ");
    string strLastName = ReadLine()!;
    
    if( (string.IsNullOrEmpty(strFirstName)) && 
        (string.IsNullOrEmpty(strMiddleName)) && 
        (string.IsNullOrEmpty(strLastName)) )
    {
        throw new System.Exception("Missing values for the first name, the middle name, and the last name.");
    }
    
    /* 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(strLastName))
        WriteLine("Full Name:   " + strFirstName);
    else
    {
        if (strMiddleName == "")
            WriteLine("Full Name:   " + string.Concat(strLastName, ", ", strFirstName));
        else
            WriteLine("Full Name:   " + string.Concat(strLastName, ", ", strFirstName, " ", strMiddleName));
    }
    
    // If the user provides only the first and last names (no middle name, ...
    if (string.IsNullOrEmpty(strMiddleName))
    {
        /* ... create a user name that uses the first letter of 
         * the first name + the whole last name. Convert the username to lower case. */
        WriteLine($"Username:    {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. */
        WriteLine($"Username:    {strFirstName.Substring(0, 1)}{strMiddleName.Substring(0, 1)}{strLastName}".ToLower());
    }
    
    WriteLine("==================================");
  2. To execute the project, on the main menu, click Debug -> Start Without Debugging
  3. When requested, type the First Name as Jennifer and press Enter
  4. When the Middle Name is requested, simply press Enter
  5. When the Last Name is requested, type Garrison and press Enter:
    First Name:  Jennifer
    Middle Name:
    Last Name:   Garrison
    Full Name:   Garrison, Jennifer
    username:    jgarrison
    ==================================
    
    Press any key to close this window . . .
  6. 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:

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:

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-2024, FunctionX Thursday 14 October 2021 Next