© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2022
G. ByrneTarget C#https://doi.org/10.1007/978-1-4842-8619-7_15

15. String Handling

Gerard Byrne1  
(1)
Belfast, Ireland
 

String Handling and Manipulation

In the previous chapter, we gained knowledge of interfaces and abstract classes and their relationship with classes and objects. We saw that interfaces and abstract classes can be used to make classes have a consistency when they inherit from the interface or abstract class. We also read that many developers will program to an interface, showing that interfaces form an integral part of developing C# applications in a commercial environment.

In this chapter we will study in more detail the use of Strings and see how we can use and manipulate them within our C# code. Throughout our chapters we used Strings, and in many of our coding examples, we have seen how we can concatenate a string to another string or to a non-string data type , which has been converted to a string. When we look back to Chapter 6, we can see that string is not one of the primitive data types, whereas char is. So we know that String as a data type is special. Just look at the fact that we have used a capital S when writing it here. Having studied classes and objects in Chapter 13, we might also think that the capital S might suggest that it is a class, as classes by convention start with a capital letter. Indeed, we are correct in this assumption, and we would say that String is a class within .NET in the System namespace . The fully qualified name of the String class is System.String, and string in C# is a shortcut for System.String.

From the code we have already developed, we should be aware that strings are very important in C# applications, and we have taken strings and converted them to other data types so that they could be used in calculations. Such examples make us realize that not all data entered into our application will be as we require. Let us look at some examples to help us better understand this:
  • A customer may need to enter their personal details into an online form and submit the form so the data can be stored in a company database. However, the customer, like myself, might not be the best “typist ” and may enter uppercase or lowercase or a mixture of cases when entering their details. Does the company really want to store this poorly formed string of data in its database? Probably not. In developing the code, we could convert the data to upper, to lower, or to proper case through our C# code, thereby standardizing the stored format.

  • A customer may need to complete an online form and include their account number. As they enter their account number, they add an extra space at the start or end. In developing the code, we need to read this account number and check if it exists, before we let the customer see their account details. As the extra space is included, our code will not be able to match the account number. Our code must check for extra spaces at the start or end of a string and take appropriate action to correct the string.

  • A customer may need to enter their credit card number, and it is known that this should be 16 digits with no spaces and in the correct format. As developers we need to check that there are 16 digits, not less or more, and in our code we will need to check that there is not a mixture of numbers and characters or even all characters.

  • Data read from a text file might need to be dissected and parsed for various reasons such as getting the customer postcode or date of birth.

  • Data being written to a database from our application needs to be validated, manipulated, and then written, to reduce the possibility of errors happening during the writing process.

In dealing with all the preceding situations, and many more, we can make use of string manipulation, yet another “tool” offered to us by .NET and one we will make good use of in many of our applications. The String class comes with its own methods and fields and we will now explore some of these. However, it is important to remember that all of the String methods and C# operators that appear to modify a string actually return the results in a new string object. We say that a string is immutable . Immutable means we cannot change the contents of a string, so what happens is that a new string object is created and the variable that pointed to the old string is now pointed to the new string object. Interestingly, if we think of strings in terms of memory usage and allocation, they are – to say the least – “poor.”
string accountNumber = "AB123456";
accountNumber = accountNumber.Replace("AB", "GB");
Listing 15-1

Example string replacement

In Listing 15-1 we are trying to replace the characters AB with the characters GB in the string and assign the returned value to the string, but as the string accountNumber cannot be changed – it is immutable – a new string object is created and accountNumber is simply pointed to this new object in its new memory location, as shown in Figure 15-1.

A diagram depicts the string account numbers, for the older pointer is A B 1 2 3 4 5 6 and the new pointer is G B 1 2 3 4 5 6.

Figure 15-1

Immutable string – new object is created

String Literals

C# has two types of string literals , verbatim and regular strings:
  • Verbatim string

    The first type of string literal is the verbatim string . When we create a verbatim string, there will be an @ symbol at the start of the string, informing the string constructor to ignore any escape characters and line breaks. Verbatim means exact, so when we use the @ symbol, we are saying, “Use the string exactly as it is written.” We will see as we code examples in this chapter that escape characters are special characters, for example, represents a new line and represents a tab.

String  message = @" C# programming console applications";
Console.WriteLine(message);
Listing 15-2

Example verbatim string

In Listing 15-2 the code includes the escape sequences and as part of the string, but they are not taken to mean new line and tab, because we have used the @ symbol. When the code is compiled and run, the output will be as shown in Figure 15-2.

A diagram depicts the string message including backslash n and backslash t as escape sequences. They do not mean a new line and tab because of the at symbol.

Figure 15-2

Verbatim displays the line exactly as it is written

Attempting to add an extra backslash in a verbatim string does not work, as we are saying we want the string to be exactly as it is. The \ approach works in other situations like assigning a file path name to a string variable, but it will not work with verbatim, only in a regular string. The escape sequences \n and \t in Listing 15-3 are part of the string, and the output will be as shown in Figure 15-3.
String  message = @"\n C# programming \t console applications";
Console.WriteLine(message);
Listing 15-3

Example verbatim string using double backslash

A diagram depicts the string message, including the double backslash n and double backslash t escape sequences, respectively.

Figure 15-3

Trying a double slash \ does not work with verbatim

  • Regular string

    The second type of string literal is the regular string . When we create a regular string literal, it means the string will be read and special characters will need to be “escaped” with a .

string message = " C# programming console applications";
Console.WriteLine(message);
Listing 15-4

Example regular string

The escape sequences and in Listing 15-4 are not taken as part of the string; they are to be taken to mean new line and tab. We have not used the verbatim symbol, @, so the output will be as shown in Figure 15-4.

A diagram depicts the string message for a newline as well as a tab for the regular string.

Figure 15-4

Regular string

If we want the and to be displayed when using a regular string, we use the \, double backslash , as shown in Listing 15-5, and the output will be as shown in Figure 15-5.
string message = "\n C# programming \t console applications";
Console.WriteLine(message);
Listing 15-5

Example regular string with double backslash

A diagram depicts the string message for backlash n and backlash t for the regular string.

Figure 15-5

Regular string with \, a double backslash

Let's code some C# and build our programming muscle.

Add a new project to hold the code for this chapter.
  1. 1.

    Right-click the solution CoreCSharp.

     
  2. 2.

    Choose Add.

     
  3. 3.

    Choose New Project.

     
  4. 4.

    Choose Console App from the listed templates that appear.

     
  5. 5.

    Click the Next button.

     
  6. 6.

    Name the project Chapter15 and leave it in the same location.

     
  7. 7.

    Click the Next button.

     
  8. 8.

    Choose the framework to be used, which in our projects will be .NET 6.0 or higher.

     
  9. 9.

    Click the Create button.

    Now we should see the Chapter15 project within the solution called CoreCSharp.

     
  10. 10.

    Right-click the project Chapter15 in the Solution Explorer panel.

     
  11. 11.

    Click the Set as Startup Project option.

    Notice how the Chapter15 project name has been made to have bold text, indicating that it is the new startup project and that it is the Program.cs file within it that will be executed when we run the debugging .

     
  12. 12.

    Right-click the Program.cs file in the Solution Explorer window.

     
  13. 13.

    Choose Rename.

     
  14. 14.

    Change the name to Strings.cs.

     
  15. 15.

    Press the Enter key.

     
  16. 16.

    Double-click the Strings.cs file to open it in the editor window.

     
  17. 17.

    Amend the code, as in Listing 15-6, with the namespace, the class, and Main().

     
namespace Chapter15
{
  internal class Strings
  {
    static void Main(string[] args)
    {
    } // End of Main() method
  } // End of Strings class
} // End of Chapter15 namespace
Listing 15-6

Class with the Main() method

We will now create code that uses String class methods and properties and demonstrates their use in practical examples. We will start with the Substring method.

Substring

The Substring() method has two forms that can be used:
  • Substring(Int32 startposition)

    In this format the Substring method will retrieve a substring of the full string starting at the specified character position and continuing to the end of the string.

  • Substring(Int32 startposition, Int32 length)

    In this format the Substring method will retrieve a substring starting at the specified character position and continuing for the specified number of characters as indicated by the length.

We will now create a string variable to hold a vehicle registration number. We will use the String data type, with a capital S, to emphasize the idea that we are dealing with a class. Remember we could use string or String.
  1. 1.

    Amend the code, as in Listing 15-7.

     
    static void Main(string[] args)
    {
      String myVehicleRegistration = "ZER 7890";
    } // End of Main() method
Listing 15-7

Set up a string and assign it a value

We will now write the code to find the characters of the string from position 4 to the end of the string object.
  1. 2.

    Amend the code as in Listing 15-8.

     
    static void Main(string[] args)
    {
      String myVehicleRegistration = "ZER 7890";
      /*
      Use the Substring() method to find the first string
      characters of the myVehicleRegistration string, starting
      at position 4 and reading to the end of the string.
      */
      Console.WriteLine("The characters from position 4 are: "
        + myVehicleRegistration.Substring(4));
Listing 15-8

Characters of the string starting at position 4

  1. 3.

    Click the File menu.

     
  2. 4.

    Choose Save All.

     
  3. 5.

    Click the Debug menu.

     
  4. 6.

    Choose Start Without Debugging.

    Figure 15-6 shows the console window displaying the characters of the zero-indexed string from position 4, the fifth element.

     

A console window indicates the zero-indexed string starting at position 4, which are 7, 8, 9, and 0.

Figure 15-6

Position 4 to the end of the string

  1. 7.

    Press the Enter key to close the console window.

    Continuing with this code, we will add new code to demonstrate different string handling methods and features. We will add the code after the existing code, just above the end curly brace of the Main() method . We will continue now by coding the statements to find the characters from position 0 to position 2, the first three characters, of the myVehicleRegistration String object.

     
  2. 8.

    Amend the code, as in Listing 15-9.

     
      Console.WriteLine("The characters from position 4 are: "
        + myVehicleRegistration.Substring(4));
      /*
      Use the Substring() method to find the first 3 characters
      of the myVehicleRegistration string.
      Remember substring is inclusive of the char at the first
      position but exclusive of the char at the end position we
      say it is inclusive/exclusive
      */
      Console.WriteLine("The first 3 characters are: "
        + myVehicleRegistration.Substring(0, 3));
    } // End of Main() method
  } // End of Strings class
} // End of Chapter15 namespace
Listing 15-9

First three characters using Substring

  1. 9.

    Click the File menu.

     
  2. 10.

    Choose Save All.

     
  3. 11.

    Click the Debug menu.

     
  4. 12.

    Choose Start Without Debugging.

    Figure 15-7 shows the console window displaying the first three characters.

     

A console window indicates the first three characters, Z, E, and R.

Figure 15-7

First three characters of the string

  1. 13.

    Press the Enter key to close the console window.

     

Length

The Length property will return an integer that represents the number of char values in the string. The code behind the Length property will count spaces in the string as they are also characters.
  1. 1.

    Amend the code to find the number of characters in the string called myVehicleRegistration, as in Listing 15-10.

     
      Console.WriteLine("The first 3 characters are: "
        + myVehicleRegistration.Substring(0, 3));
      /*
      Use the Length property from the String class to find the
      number of characters in the myVehicleRegistration object.
      */
      Console.WriteLine("The number of characters is: "
        + myVehicleRegistration.Length);
    } // End of Main() method
Listing 15-10

Find the length of a string

  1. 2.

    Click the File menu.

     
  2. 3.

    Choose Save All.

     
  3. 4.

    Click the Debug menu.

     
  4. 5.

    Choose Start Without Debugging.

    Figure 15-8 shows the console window displaying the number of characters in the string as 8.

     

A console window indicates the string contains eight characters.

Figure 15-8

The length of a string

  1. 6.

    Press the Enter key to close the console window.

     

StartsWith( )

In coding our insurance application, we might need to find a specific character or characters in a vehicle registration number since an accident involved a vehicle with the specific character(s). For this situation we could use the StartsWith() method. There are two forms of this method, method overloading, that we will use.

The StartsWith() method has two forms:

  • StartsWith(Char)

    In this format the StartsWith() method will return a Boolean value of true or false, depending on whether the String object begins with the specific char or chars. The method starts at character 0.

  • StartsWith(String)

    In this format the StartsWith() method will return a Boolean value of true or false, depending on whether the String object begins with the specific string. The method starts at character 0.

  1. 1.

    Amend the code, as in Listing 15-11, to add an array of strings.

     
      Console.WriteLine("The number of characters is: "
        + myVehicleRegistration.Length);
      // Create an array of String objects
      String[] myVehicleRegistrations = new String[] { "ZER 7890", "ZAC 7124", "ARC 3330" };
    } // End of Main() method
Listing 15-11

Declare and create an array of strings

  1. 2.

    Amend the code, as in Listing 15-12, to iterate the array and display those strings that start with (StartsWith()) the character Z.

     
      String[] myVehicleRegistrations = new String[] { "ZER 7890", "ZAC 7124", "ARC 3330" };
      foreach (String registration in myVehicleRegistrations)
      {
        if (registration.StartsWith(‘Z’))
        {
          Console.WriteLine(String.Format(" The registration {0} starts with the letter Z", registration));
        } // End of if block
        else
        {
         Console.WriteLine(String.Format(" The registration {0} does not start with the letter Z", registration));
        } // End of else block
      } // End of for each iteration
    } // End of Main() method
Listing 15-12

Find strings that start with the character Z and display them

  1. 3.

    Click the File menu.

     
  2. 4.

    Choose Save All.

     
  3. 5.

    Click the Debug menu.

     
  4. 6.

    Choose Start Without Debugging.

    Figure 15-9 shows the console window displaying each array member and stating if it begins with the character Z.

     

A console window indicates each component of the array and indicates whether or not it starts with the character Z.

Figure 15-9

Strings starting with Z

  1. 7.

    Press the Enter key to close the console window.

     

Split( )

In coding our insurance application , we might need to read a file or database, which contains data. The format of the file might be that each part is separated by a comma or a tab or a - or a space. We will need to find the data from within the file, and for this situation we could use the Split() method, which will split the data at the specified value. The Split() method will return an array of strings after it has split the string object at the specified expression. We will split each value in our registration array at the space, and we will put each of the parts of the split into a new array, which we will call splitRegistration. The Split() method has different options in the form of method overloads.
  1. 1.

    Amend the code, as in Listing 15-13.

     
      Console.WriteLine(String.Format(" The registration {0} starts with the letter Z", registration));
    } // End of if block
    else
    {
      Console.WriteLine(String.Format(" The registration {0} does not start with the letter Z", registration));
    } // End of else block
  } // End of for each iteration
  // Iterate the array and split the items as they are read
  foreach (String registration in myVehicleRegistrations)
  {
    // Array to hold the 2 parts of the vehicle registration
    String[] splitRegistration = new String[2];
    // Split the array at the space
    splitRegistration = registration.Split(' ');
    Console.WriteLine(String.Format(" Part 0 is {0}", splitRegistration[0]));
    Console.WriteLine(String.Format(" Part 1 is {0}", splitRegistration[1]));
  } // End of iteration for splitting at the space character
 } // End of Main() method
Listing 15-13

Split the strings at the spaces

  1. 2.

    Click the File menu.

     
  2. 3.

    Choose Save All.

     
  3. 4.

    Click the Debug menu.

     
  4. 5.

    Choose Start Without Debugging.

    Figure 15-10 shows the console window displaying each of the array members in their two parts, split at the space character .

     

A console window indicates every single member of the array broken down into its two components, separated by the space character.

Figure 15-10

New strings created from original strings split at spaces

  1. 6.

    Press the Enter key to close the console window.

    We can also split on multiple characters, delimiters, or regular expressions.

     
  2. 7.

    Amend the code, as in Listing 15-14, to add a new array, called myMixedVehicleRegistrations .

     
   // Create a new array of String objects
   String[] myMixedVehicleRegistrations = new String[]{ "ZER 7890", "ZAC_7124", "ARC,3330" };
 } // End of Main() method
Listing 15-14

Add a new array called myMixedVehicleRegistrations

We will now iterate the new array, myMixedVehicleRegistrations, and split each String object member of the array at the underscore, space, or comma and put the result into the splitMixedRegistration array which we will create, as shown in Listing 15-15.
  1. 8.

    Amend the code, as in Listing 15-15.

     
String[] myMixedVehicleRegistrations = new String[]
{ "ZER 7890", "ZAC_7124", "ARC,3330" };
// Iterate the array and split the items as they are read
foreach (String mixedRegistrationPart in myMixedVehicleRegistrations)
 {
// Array to hold the 2 parts of the vehicle registration
 String[] splitMixedRegistration = new String[2];
 // Split the array at the underscore, space or ,
  splitMixedRegistration
     = mixedRegistrationPart.Split(new char[] { ' ', ',', '_' });
  Console.WriteLine(String.Format(" Part 0 is {0} is ", splitMixedRegistration[0]));
  Console.WriteLine(String.Format(" Part 1 is {0} is ", splitMixedRegistration[1]));
  } // End of for each iteration
} // End of Main() method
Listing 15-15

Split the strings at the required delimiters

  1. 9.

    Click the File menu.

     
  2. 10.

    Choose Save All.

     
  3. 11.

    Click the Debug menu.

     
  4. 12.

    Choose Start Without Debugging.

    Figure 15-11 shows the console window displaying new strings.

     

A console window indicates three new strings that are generated by splitting the original strings at their respective delimiters.

Figure 15-11

New strings created from original strings split at the delimiters

  1. 13.

    Press the Enter key to close the console window.

     

CompareTo( )

In coding our insurance application , we might need to compare two strings. We could be asking a customer to enter their account reference and then comparing it with account references read from a file so we can display data related to this specific customer. To undertake the comparison, we could use the CompareTo() method of the String class. Interestingly, the CompareTo() method is an implementation of the interface method CompareTo() that exists in the interface IComparable. We have just completed a chapter on interfaces where we talked about interfaces and interface methods, and this is a great example of an implementation of an interface method.

In string handling the CompareTo() method will compare two string objects or strings and return an integer that indicates a position for the comparing string, as per the following rules:
  • If the string being compared precedes the other string, it returns an integer less than zero.

  • If the string being compared is in the same position as the other string, it returns a 0, zero.

  • If the string being compared follows the other string, it returns an integer greater than zero.

When dealing with strings, the comparison is based on the lexical relationship between the two objects, which essentially means alphabetical order. We can think of it as the dictionary order of the word where digits come before letters and lowercase letters come before uppercase ones.
  1. 1.

    Amend the code, as in Listing 15-16, to add a new array called myDuplicateVehicleRegistrations with additional String objects.

     
        Console.WriteLine(String.Format(" Part 1 is {0}" +
          " is ", splitMixedRegistration[1]));
      } // End of for each iteration
      // Create a new array of String objects
      String[] myDuplicateVehicleRegistrations = new String[] { "ZER 7890", "ZAC_7124", "ARC,3330", "ZER 7890", "ARC,3330", "zer 7890", " zac_7124" };
    } // End of Main() method
Listing 15-16

New array

Finding Matching Strings

We will add code to iterate the new array and compare each String object with each of the other String objects and output a message to say if the Strings are the same. This will require an inner iteration.
  1. 2.

    Amend the code, as in Listing 15-17.

     
// Create a new array of String objects
String[] myDuplicateVehicleRegistrations = new String[]
{ "ZER 7890", "ZAC_7124", "ARC,3330", "ZER 7890",
  "ARC,3330", "zer 7890", " zac_7124" };
// Iterate the array and split the items as they are read
for (int counter = 0; counter <
        myDuplicateVehicleRegistrations.Length; counter++)
{
  for (int innercounter = counter + 1; innercounter <
      myDuplicateVehicleRegistrations.Length; innercounter++)
  {
    if (myDuplicateVehicleRegistrations[counter].CompareTo(myDuplicateVehicleRegistrations[innercounter]) == 0)
    {
      Console.WriteLine(String.Format(" {0} at index {1} is the same String as array index {2} {3}", myDuplicateVehicleRegistrations[counter],counter,innercounter,myDuplicateVehicleRegistrations[innercounter]));
    } // End of the if selection block
  } // End of for inner loop iteration
} // End of for each outer loop iteration
} // End of Main() method
Listing 15-17

Iterate the array and find strings that are the same

  1. 3.

    Click the File menu.

     
  2. 4.

    Choose Save All.

     
  3. 5.

    Click the Debug menu.

     
  4. 6.

    Choose Start Without Debugging.

    Figure 15-12 shows the console window displaying strings that have been compared as the same. This means a value less than zero was returned when the two strings were compared.

     

A console window indicates similar strings that are compared to strings that return a value smaller than zero.

Figure 15-12

Equal strings

  1. 7.

    Press the Enter key to close the console window.

    Finding Which Strings Precede Other Strings

    We will add code at the end of the Main() method to iterate the new array and compare each String object with each of the other String objects, displaying a message when a string comes before, precedes, another string.

     
  2. 8.

    Amend the code, as in Listing 15-18.

     
  // Iterate the array and split the items as they are read
  for (int counter = 0; counter < myDuplicateVehicleRegistrations.Length; counter++)
  {
    for (int innercounter = counter + 1; innercounter < myDuplicateVehicleRegistrations.Length; innercounter++)
    {
      if (myDuplicateVehicleRegistrations[counter].CompareTo(myDuplicateVehicleRegistrations[innercounter]) == 1)
      {
        Console.WriteLine(String.Format(" String {0} comes after String {1}", myDuplicateVehicleRegistrations[counter],myDuplicateVehicleRegistrations[innercounter]));
      } // End of if block
    } // End of for inner loop iteration
  } // End of for each outer loop iteration
} // End of Main() method
Listing 15-18

Iterate the array and find strings that precede other strings

  1. 9.

    Click the File menu.

     
  2. 10.

    Choose Save All.

     
  3. 11.

    Click the Debug menu.

     
  4. 12.

    Choose Start Without Debugging.

    Figure 15-13 shows the console window displaying the strings that come before other strings in the array.

     

A console window depicts the strings that are indicated in the array's order of appearance before any other strings.

Figure 15-13

Strings in the array that precede other strings

  1. 13.

    Press the Enter key to close the console window.

     

ToUpper( ) and ToLower( )

In coding our insurance application , we might need to compare two strings, but we need to be sure the strings are in the correct case. There is no point in having the customer enter their account reference in mixed-case lettering and then trying to compare it for equality with our data, which is in uppercase. To solve this issue, we could use the ToUpper() method of the String class to convert the user input to match our uppercase data. We could equally apply the same principle to a scenario where we need to use lowercase.

In string handling the ToUpper() method will convert the characters of the string into uppercase characters, when there is an equivalent uppercase character.

In string handling the ToLower() method will convert the characters of the string into lowercase characters, when there is an equivalent lowercase character.

We will add code to convert the String objects to uppercase when we are comparing them. This code is the same iteration as we have just used, but we use the ToUpper() method on both strings being compared.
  1. 1.

    Add the code in Listing 15-19.

     
/*
Iterate the array and compare the items, changing to
upper case, as they are read
*/
for (int counter = 0; counter <
        myDuplicateVehicleRegistrations.Length; counter++)
{
  for (int innercounter = counter + 1; innercounter <
          myDuplicateVehicleRegistrations.Length; innercounter++)
   {
    if(myDuplicateVehicleRegistrations[counter].ToUpper().
    CompareTo(myDuplicateVehicleRegistrations[innercounter].ToUpper()) == 0)
    {
     Console.WriteLine("With upper case {0} at index {1} is " +
     "the same String as {3} at index {2} ",
     myDuplicateVehicleRegistrations[counter], counter,
     innercounter, myDuplicateVehicleRegistrations[innercounter]);
    }
  } // End of inner for iteration
} // End of outer for each iteration
} // End of Main() method
Listing 15-19

Convert both strings to uppercase using the ToUpper() method

  1. 2.

    Click the File menu.

     
  2. 3.

    Choose Save All.

     
  3. 4.

    Click the Debug menu.

     
  4. 5.

    Choose Start Without Debugging.

    Figure 15-14 shows the console window displaying the matching strings when conversion to uppercase has occurred.

     

A console window depicts the matched strings after the top upper open and close parentheses function has converted them to uppercase.

Figure 15-14

Using ToUpper() before comparing strings

  1. 6.

    Press the Enter key to close the console window.

     

We could amend the program code if we wished to test the ToLower() method.

Concat( )

In many of the applications we have coded, we have concatenated a string and a non-string value using the + symbol. Another way to concatenate when we have only string values is to use the String.Concat() static method of the String class.

Concat() will concatenate multiple strings by appending the specified Strings. The String.Concat() method returns the newly combined String of characters.

We will now amend the code to create three string literals and concatenate the strings into a message of two sentences. The concatenation includes “hard-coded” string constants and an escape character, . Ensure there is a space before the G of Gerry in the insuredPerson string, as we will use it later in an example.
  1. 1.

    Add the code in Listing 15-20.

     
String insuredPerson = " Gerry Byrne,";
String welcome = "thank you for taking out insurance with us.";
String insuranceType = "Home Insurance";
String myOfferDetails = String.Concat(insuredPerson, " ", welcome, " ", "You now have full ", insuranceType, ". ");
Console.WriteLine(String.Format(" {0}", myOfferDetails));
} // End of Main() method
Listing 15-20

Using the Concat() method to join strings

  1. 2.

    Click the File menu.

     
  2. 3.

    Choose Save All.

     
  3. 4.

    Click the Debug menu.

     
  4. 5.

    Choose Start Without Debugging.

    Figure 15-15 shows the console window displaying the concatenated strings.

     

A console window depicts four strings joined together to form one long string.

Figure 15-15

Concatenating strings

  1. 6.

    Press the Enter key to close the console window.

     

Trim ( )

We read at the start of the chapter about an example where a customer might enter their account number and accidentally add an extra space at the start or end. We said that our code would need to check for spaces at the start and end of the string input, and this is what the Trim() method can do for us. The Trim() method will remove any leading spaces, at the start, and any trailing spaces, at the end, from the string object. The method will leave spaces that exist inside the string. There is also a TrimStart() method, which is used to remove the occurrences of a set of characters from the start of the String object, while the TrimEnd() method is used to remove the occurrences of a set of characters from the end of a String object.

We will now amend the code to trim the space from the front of the insuredPerson string, remembering that we were told to insert a space before the Gerry Byrne part. We will then display the new string.
  1. 1.

    Add the code in Listing 15-21, to apply the Trim() method to the myOfferDetails variable.

     
String trimmedMyOfferDetails = myOfferDetails.Trim();
Console.WriteLine(String.Format(" {0}", trimmedMyOfferDetails));
} // End of Main() method
Listing 15-21

Remove the leading and trailing spaces using the Trim() method

  1. 2.

    Click the File menu.

     
  2. 3.

    Choose Save All.

     
  3. 4.

    Click the Debug menu.

     
  4. 5.

    Choose Start Without Debugging.

    Figure 15-16 shows the console window displaying the concatenated strings, but the leading space has been removed.

     

A console window depicts the gap at the beginning of the string has been eliminated.

Figure 15-16

Extra space at the front of the string trimmed

  1. 6.

    Press the Enter key to close the console window.

     

Replace( )

In an application we may need to replace a character or characters with different characters, and this can be achieved using the Replace() method. We may need to replace 2023 with 2024 in a date string or replace Au with AU in all auto policies.

The Replace() method has two forms:
  • Replace(old char, new char)

    In this format the method will replace all occurrences of the old character with the new character.

  • Replace(old string, new string)

    In this format the method will replace all occurrences of the old string of characters with the new string of characters.

We will amend the code to use the Replace() method to replace a character in a string and then display the new string.
  1. 1.

    Amend the code, as in Listing 15-22.

     
String name = "Gerry Byrne";
String newName = name.Replace('e', 'E');
Console.WriteLine(String.Format(" {0}", newName));
} // End of Main() method
Listing 15-22

Replace characters in a string; new string object is formed

  1. 2.

    Click the File menu.

     
  2. 3.

    Choose Save All.

     
  3. 4.

    Click the Debug menu.

     
  4. 5.

    Choose Start Without Debugging.

    Figure 15-17 shows the console window displaying the string with the two lowercase e characters replaced with uppercase E characters.

     

A console window depicts that in the string Gerry Byrne, the letter e has been capitalized and substituted with an uppercase E.

Figure 15-17

Lowercase e replaced with uppercase E

  1. 6.

    Press the Enter key to close the console window.

    We will amend the code to use the Replace() method to replace a string of characters in a string and then display the new String.

     
  2. 7.

    Amend the code as in Listing 15-23.

     
String name = "Gerry Byrne";
String newName = name.Replace('e', 'E');
Console.WriteLine(String.Format(" {0}", newName));
String newCapitalName = name.Replace("Gerry", "GERARD");
Console.WriteLine(String.Format(" {0}", newCapitalName));
    } // End of Main() method
Listing 15-23

Replace Gerry with GERARD

  1. 8.

    Click the File menu.

     
  2. 9.

    Choose Save All.

     
  3. 10.

    Click the Debug menu.

     
  4. 11.

    Choose Start Without Debugging.

    Figure 15-18 shows the console window displaying the string Gerry replaced by the string GERARD.

     

A console window depicts that in the string Gerry Byrne, the string Gerry was substituted with the string G E R A R D.

Figure 15-18

Gerry replaced with GERARD

  1. 12.

    Press the Enter key to close the console window.

     

Contains( )

In an application we may need to check if a string contains a char or a number of chars, and this can be achieved using the Contains() method. We may need to check if a policy id contains AU and then amend the monthly premium because auto insurance policies are due to be increased by 10%.

The Contains() method has two forms:

  • Contains(char)

    In this format the method will return a value indicating if a specified character occurs within a string.

  • Contains(string)

    In this format the method will return a value indicating if a specified string occurs within a string.

  1. 1.

    Amend the code, as in Listing 15-24, to use the Contains() method to see if the user has input the string Home in an answer to a question.

     
Console.WriteLine("What type of insurance do you require? ");
  String clientInsuranceType = Console.ReadLine();
  if (clientInsuranceType.Contains("Home"))
  {
    Console.WriteLine("Home Insurance types are");
    Console.WriteLine("1. Building Only");
    Console.WriteLine("2. Content Only");
    Console.WriteLine("3. Building and Content Only");
  }
  else
  {
    Console.WriteLine("You have not chosen Home Insurance");
  }
} // End of Main() method
Listing 15-24

Checking if a string input contains the string Home

  1. 2.

    Click the File menu.

     
  2. 3.

    Choose Save All.

     
  3. 4.

    Click the Debug menu.

     
  4. 5.

    Choose Start Without Debugging.

    Figure 15-19 shows the console window displaying the question.

     
  5. 6.

    Type Home in the console window and press the Enter key.

     

A console window depicts the user input string including home, and the menu is suggested to the user.

Figure 15-19

Home insurance types displayed

  1. 7.

    Press the Enter key to close the console window.

     

Figure 15-19 shows the types of home insurance because our input contained the string Home.

IndexOf( )

In our application we may wish to see if a string contains a specific character and at what position the character is located, and for this we use the IndexOf() method to check if a character is inside a string. An example might be when we are verifying a customer email address. We might want to check that it contains an @ symbol. If it does, we might be happy that the entry is a valid email address; otherwise, it is not. But we might also wish to verify that the @ is located at a specific position or index.

The IndexOf() method has two forms:
  • IndexOf(char)

    In this format the method will return the zero-based index of the first occurrence of the specified char in the string object.

  • IndexOf(string)

    In this format the method will return the zero-based index of the first occurrence of the specified string in the string object.

The IndexOf () method returns –1 if the character or string is not found.
  1. 1.

    Amend the code, as in Listing 15-25, to use the IndexOf() method to find the position of the @ char.

     
Console.WriteLine("Please enter your email address? ");
string emailAddress = Console.ReadLine();
int intPosition = emailAddress.IndexOf("@");
if (intPosition == -1)
{
  Console.WriteLine("Not a valid email address - retype your email address");
}
else
{
  Console.WriteLine("Valid email address with the @ at position "
    + intPosition);
}
} // End of Main() method
Listing 15-25

Check if IndexOf() returns –1

  1. 2.

    Click the File menu.

     
  2. 3.

    Choose Save All.

     
  3. 4.

    Click the Debug menu.

     
  4. 5.

    Choose Start Without Debugging.

    Figure 15-20 shows the console window asking for the email address .

     
  5. 6.

    Type an email address containing an @, for example, [email protected], and press the Enter key.

     

A console window depicts that there is an at symbol in the string that was input by the user.

Figure 15-20

Index of the character @

  1. 7.

    Press the Enter key to close the console window.

     

The text is checked only for an @ symbol, so this is not a very efficient email checker, but we receive a message that the email address is valid, as in Figure 15-20, because the @ symbol was located.

Insert( )

In our application we may wish to see if a string contains a specific character or string of characters, and if it does not, then we might wish to insert the character or string of characters. .NET offers us the Insert() method to place characters inside a string. As an example, we might need to verify a customer account number by checking that it contains two letters at the start. If it does, the entry can be seen as a valid account number. If it does not, then we may wish to put the two letters in front of the number based on other information the user has also entered.

The format for the Insert() method means we must specify the zero-indexed position where the insertion will take place and we must also give the character or characters to be inserted. In this example we will check if the first two characters of a string are G and B, and if they are not, we insert the value GB at position 0.
  1. 1.

    Amend the code, as in Listing 15-26.

     
Console.WriteLine("What is your account number? ");
string accountNumber = Console.ReadLine();
int intPositionG = accountNumber.IndexOf("G");
int intPositionB = accountNumber.IndexOf("B");
if (intPositionG == 0 && intPositionB == 1)
{
  Console.WriteLine("Valid account number " + "Character G was found at location " + intPositionG + " Character B was found at location " + intPositionB);
} // End of if section
else
{
  Console.WriteLine("Not a valid account number");
  accountNumber = accountNumber.Insert(0, "GB");
  Console.WriteLine("The account number is " + accountNumber);
} // End of else section
} // End of Main() method
Listing 15-26

Use the Insert method to insert the characters GB at index 0

  • The code finds the position of the letter G in the string and assigns it to the variable intPositionG.

  • The code finds the position of the letter B in the string and assigns it to the variable intPositionB.

  • The next part uses the if statement to see if the letters G and B have been located at the start of the string in the positions 0 and 1.

  • If they have been found, then a message is displayed saying that the account number is valid and telling us the position of the two letters.

  • If the two letters are not found, then a message is displayed saying that the account number is invalid.

  • The letters GB are then inserted into the string starting at position 0. Remember that we are using the Insert() method, not the Replace() method.

  • The console will show the string with the GB added at the start.

  1. 2.

    Click the File menu.

     
  2. 3.

    Choose Save All.

     
  3. 4.

    Click the Debug menu.

     
  4. 5.

    Choose Start Without Debugging.

    The console window will appear and ask the user to input their account number. We know it should begin with the string GB or, put another way, G should be the first character and B should be the second character. If this is not what is entered, the code will insert GB at the start of the entered string. Obviously, we could have used the Replace() method, but we are trying to understand the Insert() method.

     
  5. 6.

    Type AB123456, an invalid input, and press the Enter key.

    Figure 15-21 shows the console window with GB prefixed to the string.

     

A console window depicts that if the first two characters are not G B, they are modified to reflect the prefix.

Figure 15-21

Insert GB as the first two characters if they are not already GB

  1. 7.

    Press the Enter key to close the console window.

     
  2. 8.

    Click the File menu.

     
  3. 9.

    Choose Save All.

     
  4. 10.

    Click the Debug menu.

     
  5. 11.

    Choose Start Without Debugging.

     
  6. 12.

    Type GB123456, a valid input, and press the Enter key.

    Figure 15-22 shows the console window with the indexes of G and B shown, after we have entered the input required.

     

A console window depicts a G as the very first character in the user input string and a B as the very second character.

Figure 15-22

No replacement needed

  1. 13.

    Press the Enter key to close the console window.

     

String.Format( )

We will continue the use of the String class , but we will now look at how we have already used the Format() method of the String class to contain a string and placeholders for variables or objects.

In many of our code applications , we have displayed to the console using two different formats:
  • The first format has been to use the Console.WriteLine() method where we have concatenated a string literal with a variable. In this case the variable becomes a string and is joined onto the string literal, and then the whole string is displayed. Listing 15-27 shows an example that we have already coded.

Console.WriteLine("The number of characters is: " + myVehicleRegistration.Length);
Listing 15-27

Using Console.WriteLine()

  • The second format has been to use the Console.WriteLine() method where we have included the String.Format() method to format the string. We use String.Format() when we wish to insert a variable, object, or expression within our string. Listing 15-28 shows an example that we have already coded.

Console.WriteLine(String.Format(" The registration {0} does not start with the letter Z", registration));
Listing 15-28

Using String.Format()

The {0} is a placeholder within the format string. The 0 refers to the index of the object whose string value will be inserted at that position, and in Listing 15-28 this is the variable called registration. If the placeholder refers to an object that is not a string, then the ToString() method of the object will be called, and the object will be converted to a string, which is placed at the position of the placeholder.

We can have as many placeholders as we require so long as there is a matching object after the comma (,) following the end double quote. We say that there is an object list after the comma following the end double quote.

Formatting the Items in the String

When we use the placeholder like {0} in Listing 15-28, it refers to an object in the object list, and if the object is a string, this is an easy insertion. If we have a different data type to be inserted, like a double, we may wish to format it to two decimal places or some other type of formatting. With placeholders we can add some control to them, and in the widely used case of the double or float data type, we could do {0:d}. We can also use a similar approach for a time object, where we could do {1:t}, remembering that we can have more than one object in the string, and that is why we have the number 1 in the curly braces. There are a number of types in C# that are supportive of format strings, including all numeric types, dates, and times. Listing 15-29 shows some code examples, with comments, and their output.
  1. 1.

    Amend the code, as in Listing 15-29, to use some String.Format() methods.

     
// Format the number to 2 decimal places giving 99.97
Console.WriteLine(String.Format("Decimal: {0:0.00}", 99.9687));
// Format to scientific format 9.99E+002
// (E+002 is 10 to the power of 2 or 100)
Console.WriteLine(String.Format("Scientific: {0:E}", 999));
// Format to local currency format e.g. 2 decimal places
// and a £ symbol £99.97
Console.WriteLine(String.Format("Currency:{0:C}", 99.9687654));
// Format to percent 99 multiplied by 100 is 9900%.
Console.WriteLine(String.Format("Percent: {0:P}", 99));
DateTime localDate = DateTime.Now;
// Format the string as a short time
Console.WriteLine(String.Format("Short date:{0:t}", localDate));
// Format the string as a long time
Console.WriteLine(String.Format("Long date: {0:F}", localDate));
} // End of Main() method
Listing 15-29

Using String.Format() with formatting

  1. 2.

    Click the File menu.

     
  2. 3.

    Choose Save All.

     
  3. 4.

    Click the Debug menu.

     
  4. 5.

    Choose Start Without Debugging.

    Figure 15-23 shows the console window after we have entered the inputs required.

     

A console window depicts the required entered inputs that have been completed by utilizing the string dot format open and close parentheses.

Figure 15-23

Output when using String.Format()

  1. 6.

    Press the Enter key to close the console window.

     

String Interpolation

We will continue the use of the String class , but we will now look at how we can use string interpolation to format a string to be used in the WriteLine() method.

We have been coding using what is called composite formatting , which is fine, and we have used it successfully to display our output. However, from C# 6 the recommended way to do the same thing is by using string interpolation because it is more flexible and the code is easier to read. String interpolation introduces us to the use of the special character $, which identifies the string literal as an interpolated string. An interpolated string is a string literal that might contain interpolation expressions. Whoa, hold on. What does this word interpolation even mean? Well, it means

The insertion of something of a different

nature into something else

For us it is a fancy word for joining our strings with other non-string variables or values, and to build a string interpolation, we will have the following:
  • The start as a $

  • Next, open and close "" double quotes

  • Then, inside the double quotes, our string

  • Next to the string, open and close curly braces {} to hold an object

  • Then, inside the open and close curly braces {}, the object and any formatting

    All this will be within the () of the WriteLine().

Listing 15-30 shows some code examples, with comments, and their output.
  1. 1.

    Amend the code, as in Listing 15-30.

     
  // Format  the number to 2 decimal places giving 99.97
  Console.WriteLine($"Decimal: {99.9687:0.00}");
  // Format to scientific format giving 9.99E+002
  // E+002 is 10 to the power of 2 or 100)
  Console.WriteLine($"Scientific: {999:E}");
  // Format to local currency format e.g. 2 decimal places
  // and a £ symbol £99.97
  Console.WriteLine($"Currency: {99.9687654:C}");
  // Format to percent 99 multiplied by 100 is 9900%
  Console.WriteLine($"Percent: {99:P}");
  DateTime localDate2 = DateTime.Now;
  // Format the string as a short time
  Console.WriteLine($"Short time: {localDate2:t}");
  // Format the string as a long time
  Console.WriteLine($"Long date: {localDate2:F}");
} // End of Main() method
Listing 15-30

Using string interpolation

  1. 2.

    Click the File menu.

     
  2. 3.

    Choose Save All.

     
  3. 4.

    Click the Debug menu.

     
  4. 5.

    Choose Start Without Debugging.

    Figure 15-24 shows the console and confirms that we get the same output as Figure 15-23, which uses the code shown in Listing 15-29, but we should be thinking that our code is easier to read and therefore will be easier to maintain.

     

A console window depicts a single object in the display line and is used to confirm the interpolation.

Figure 15-24

Interpolation with a single object in the display line

  1. 6.

    Press the Enter key to close the console window.

    In the code of Listing 15-30, we have used one object in the interpolation, so let us code an example that uses more than one object.

     
  2. 7.

    Amend the code, as in Listing 15-31, to use multiple objects in the interpolation.

     
Console.WriteLine($"Decimal: {99.9687654:0.00} Scientific: {999:E} Currency: {99.9687654:C}");
 Console.WriteLine($"The Short date is {localDate:t} while the long date is {localDate:F}");
} // End of Main() method
Listing 15-31

Using string interpolation with more than one object

  1. 8.

    Click the File menu.

     
  2. 9.

    Choose Save All.

     
  3. 10.

    Click the Debug menu.

     
  4. 11.

    Choose Start Without Debugging.

    Figure 15-25 shows the console window displaying the formatted objects in each of the two display lines.

     

A console window depicts that each of the two display lines' formatted objects was interpolated to fit more elements.

Figure 15-25

Interpolation with multiple objects in the display line

  1. 12.

    Press the Enter key to close the console window.

     

String Interpolation: Spacing

We also have the option of controlling spacing within the interpolation by using the alignment component. This component uses a signed integer where
  • A negative means align left.

  • A positive means align right.

If there is a situation where the string is larger than the amount of spacing set aside, then the alignment is ignored and the length of the string will be used for the field width, therefore overriding the user-assigned numeric value. The padding required to make the string the correct alignment will consist of white spaces. Listing 15-32 shows some code examples, with comments, and their output.
  1. 1.

    Amend the code, as in Listing 15-32, to use spacing in string interpolation.

     
/*
Spacing is achieved using - for left and + for right alignment
In this example we have the first string right aligned in its
20 spaces, the second string left aligned in its 25 spaces,
*/
 Console.WriteLine($"The Short time is {localDate:t} while the long date is {localDate:F}");
 Console.WriteLine($"{"The Short time is",20} {localDate:t} {"while the long date is",-25}{ localDate:F}");
} // End of Main() method
Listing 15-32

Using string interpolation with control of spacing

  1. 2.

    Click the File menu.

     
  2. 3.

    Choose Save All.

     
  3. 4.

    Click the Debug menu.

     
  4. 5.

    Choose Start Without Debugging.

    Figure 15-26 shows the console window displaying, in the second line, the right- and left-aligned formatted objects.

     

A console window depicts the second line, the formatted objects with a right alignment of 20 and a left alignment of 25.

Figure 15-26

Second line is controlled using left and right alignment

  1. 6.

    Press the Enter key to close the console window.

     

@ Verbatim

Sometimes in our strings , we will want to use characters such as a backslash, , and double quotes, " , but the compiler thinks they are code sequences and tries to “interpret” them. There will be other times when we want to use escape sequences such as for a new line and for a tab, and in order to achieve this we can use another backslash, , in front of the escape sequence . Often, we will see the in code that uses a path name for a file, for example:

"C:DesktopGerryCode est.cs"

We will see this in the next chapter on file handling. In the path name we have backslashes and double quotes ", which can cause errors in our code. Listing 15-33 shows some code examples, with comments, and their output.
  1. 1.

    Amend the code, as in Listing 15-33, to use the double backslash in string interpolation.

     
/*
Escape sequences
In this example we use the backslash in front of the which
is the escape sequence for a new line
*/
Console.WriteLine("Two character pair for a new line is \n");
/*
Escape sequences
In this example we use the backslash in front of the starting
double quote " to indicate that we wish the " to be displayed
We then use the backslash in front of the which is the
escape sequence for a new line and we are saying we want this
to be displayed and finally we use the backslash in front
of the ending double quote " to indicate that we wish
the " to be displayed
*/
Console.WriteLine("Two character pair for a new line is "\n" ");
} // End of Main() method
Listing 15-33

Using \ to make the compiler read the sequence literally

  1. 2.

    Click the File menu.

     
  2. 3.

    Choose Save All.

     
  3. 4.

    Click the Debug menu.

     
  4. 5.

    Choose Start Without Debugging.

    Figure 15-27 shows the console window displaying the in the first display line and the double quotes and in the second line.

     

A console window depicts the second display line's double quotes and backslash n. The first display line is backslash n.

Figure 15-27

Output from \, double backslash sequence

  1. 6.

    Press the Enter key to close the console window.

    Unfortunately we may have a number of these backslashes in our strings, and it can be tedious to type the string and it also makes the code hard to read, for example:

    "C:\Desktop\Gerry\Code\test.cs"

    So another way to do the same thing is to use verbatim, the @ symbol. Using the verbatim @ symbol means backslashes are not interpreted as escape characters. However, the downside is that we cannot have special characters in our string when using verbatim. Another idiosyncrasy is when we want to display a double quote. We need to precede the double quote with another double quote. Listing 15-34 shows the same code examples as Listing 15-33, with comments, and their output.

     
/*
@ Verbatim
There is an alternative way to the \ when we wish to display
or use a
The alternative is to use a verbatim string which means we use
a regular string but we put a @ symbol before the opening
double quotes. The verbatim now treats all characters in a
literal way, just as they appear
*/
Console.WriteLine(@"Two character pair for a new line is ");
/*
There is an exception when using the verbatim and that is when
we are wanting to display the double quote character ".
As the " indicates the start and the end of the verbatim string
how can we add them if we want to actually display them?
We might think use the backslash . But no, we use another
double quote in front of the double quote to be displayed as
shown in this example.
*/
Console.WriteLine(@"Two character pair for a new line is "" """);
Listing 15-34

Using verbatim, @

  1. 7.

    Click the File menu.

     
  2. 8.

    Choose Save All.

     
  3. 9.

    Click the Debug menu.

     
  4. 10.

    Choose Start Without Debugging.

    Figure 15-28 shows the console window displaying the in the first display line and the double quotes and in the second line, but this time we have used the verbatim style.

     

A console window depicts the utilized verbatim style for the backslash n in the first display line and double quotes and backslash n in the second.

Figure 15-28

Output from using verbatim, @

  1. 11.

    Press the Enter key to close the console window.

     

Now we will look at using the verbatim, @, symbol alongside the string interpolation, $, symbol. We will see how C# 8, C# 10, and above handle the use and mixing of these symbols .

Wh at About $@ or @$?

While coding an application, we may also have a need within the string interpolation to have double quotes around something, for example, we might want to display "" as we saw in the last example using the verbatim. So, in the string interpolation, we might try to use the line of code as shown in Listing 15-35.
Console.WriteLine($"Two character pair for a new line is "" """);
Listing 15-35

Compile error when using "" within a verbatim string

However, if we were to code this line, we would get a compile error, as shown in Figure 15-29. The reason for the error is we will have reached the match for the opening double quote when we are at the first double quote after the word is.

A console window depicts the compile error where the problem occurs when it reaches the first double quote after the word is.

Figure 15-29

Compile error

From C# 7 we could fix this by using the $ symbol, followed by the verbatim @. This means we will code $@, and it is essential that the symbols are in the correct order when using C# 7. However, from C# 8 we can also have the order of the symbols reversed, and therefore we can now use @$. So, as we are coding for C# 10 and above, we can write our code as in Listing 15-36 or as in Listing 15-37, and the results will be the same, as shown in Figure 15-30.
Console.WriteLine($@"Two character pair for a new line is "" """);
Listing 15-36

In C# 7 we use $@

Console.WriteLine(@$"Two character pair for a new line is "" """);
Listing 15-37

In C# 8 onward we can also use @$

A console window depicts the coding of the statement using either a dollar symbol and an at sign or an at sign and a dollar symbol.

Figure 15-30

$@ or @$ gives the same output

From all the different ways we have looked at to display to the console, we can choose which “format” to use. What we need to consider is which format suits our coding style while at the same time making the code easy to read and therefore easier to maintain. Having personal choice also comes with responsibility.

Const String Interpolation

Prior to C# 10 we could have constant strings , where a const string is a string that cannot be modified. Prior to C# 10 we had to concatenate const strings using the +, and we could not use const strings in string interpolation, with the $. However, from C# 10 this has changed, and we can now make use of const strings within a string interpolation.

Add a new class.
  1. 1.

    Right-click the Chapter15 project.

     
  2. 2.

    Choose Add.

     
  3. 3.

    Choose Class.

     
  4. 4.

    Name the class ConstantStrings.cs.

     
  5. 5.

    Amend the code, as in Listing 15-38, to create a Main() method within the class, as this was not produced automatically, and delete the unwanted imports.

     
namespace Chapter15
{
  internal class ConstantStrings
  {
    static void Main(string[] args)
    {
    } // End of Main() method
  } // End of ConstantStrings class
} // End of Chapter15 namespace
Listing 15-38

Using const strings

Now we will create four const strings, which we will use in a concatenation.
  1. 6.

    Create a series of four const strings, as in Listing 15-39.

     
  static void Main(string[] args)
  {
    /*
    Prior to C# 10 we could have const strings and we
    had to concatenate them using the +
    */
    const string thankYou = "Thank you for purchasing insurance with us. ";
    const string offerMessageHome = "As a thank you we are offering you 10% of your next Home insurance ";
    const string offerMessageBuilding = "As a thank you we are offering you 5% of your next Building insurance ";
    const string redeemMessage = "Simply call us and we have this offer associated with your account ";
} // End of Main() method
Listing 15-39

Adding the four const strings

Now we will create a new const string for a home message, which will be formed by concatenating three of the four const strings. We will then display the new home message const string.
  1. 7.

    Amend the code as in Listing 15-40.

     
   const string redeemMessage = "Simply call us and we have this offer associated with your account ";
   // Concatenation using +
   const string homeMessage = thankYou + offerMessageHome + redeemMessage;
   Console.WriteLine(homeMessage);
    } // End of Main() method
Listing 15-40

Concatenating strings for a home message using the +

Now we will create a new const string for a building message, which will be formed by concatenating three of the four const strings. We will then display the new building message const string.
  1. 8.

    Amend the code as in Listing 15-41.

     
   // Concatenation using +
   const string homeMessage = thankYou + offerMessageHome + redeemMessage;
   Console.WriteLine(homeMessage);
   const string buildingMessage = thankYou + offerMessageBuilding + redeemMessage;
   Console.WriteLine(buildingMessage);
    } // End of Main() method
Listing 15-41

Concatenating strings for a building message using the +

  1. 9.

    Right-click the Chapter15 project in the Solution Explorer panel.

     
  2. 10.

    Choose Properties from the pop-up menu.

     
  3. 11.

    Choose the Chapter15.ConstantStrings class in the Startup object drop-down list, as shown in Figure 15-31.

     

A startup object drop-down list indicates the function of the chapter 15 dot constant strings class.

Figure 15-31

Changing the startup class in the C# project

  1. 12.

    Close the Properties window.

     
  2. 13.

    Click the File menu.

     
  3. 14.

    Choose Save All.

     
  4. 15.

    Click the Debug menu.

     
  5. 16.

    Choose Start Without Debugging.

    Figure 15-32 shows the console output displaying the concatenated const strings.

     

A console output depicts the concatenated const strings by employing the conventional plus sign in conjunction with the concatenating strings.

Figure 15-32

Concatenating strings using the traditional +

  1. 17.

    Press the Enter key to close the console window.

    Now we will use the const strings, but in an interpolated string. We will create a new home message const string and assign it the $ string interpolation, which uses the const strings. We will then display the new string to the console.

     
  2. 18.

    Amend the code, as in Listing 15-42.

     
    /*
    From C# 10 we are allowed to concatenate const strings
    with the string interpolation $
    */
    const string homeMessageConst = ($"{thankYou}{offerMessageHome}{redeemMessage}");
   Console.WriteLine(homeMessageConst);
} // End of Main() method
Listing 15-42

Interpolated string using const strings – home message

Now we will create a new building message const string and assign it the $ string interpolation, which uses the const strings. We will then display the new string to the console.
  1. 19.

    Amend the code, as in Listing 15-43.

     
   const string homeMessageConst = ($"{thankYou}{offerMessageHome}{redeemMessage}");
   Console.WriteLine(homeMessageConst);
   const string buildingMessageConst = $"{thankYou}{offerMessageBuilding}{redeemMessage}";
   Console.WriteLine(buildingMessageConst);
} // End of Main() method
Listing 15-43

Interpolated string using const strings – building message

If we look at our code and hover over the opening bracket ( in the code
($"{thankYou}{offerMessageHome}{redeemMessage}");
there may be a warning, as shown in Figure 15-33, stating that we do not require the opening and closing brackets, but it is also fine to keep the brackets.

A console window indicates that parentheses can be removed.

Figure 15-33

Warning that parentheses are not required

Also, if we are not using C# 10, we will see a message, as shown in Figure 15-34, that const strings in an interpolated string are not available.

A console window indicates that version 10.0 or higher is required for Error const strings not supported in this language.

Figure 15-34

Error – const strings not available in this language version

  1. 20.

    Click the File menu.

     
  2. 21.

    Choose Save All.

     
  3. 22.

    Click the Debug menu.

     
  4. 23.

    Choose Start Without Debugging.

    Figure 15-35 shows the console output displaying the interpolated string, which uses the const strings.

     

A console output indicates the utilization of conventional string concatenation through the plus and interpolated string through the const strings.

Figure 15-35

Interpolated string using const strings displayed

  1. 24.

    Press the Enter key to close the console window.

     

Chapter Summary

So, finishing this long chapter on string handling, we should remember that a string or String is one of the built-in reference value types. String is a class, and therefore it has methods and properties just like any other class. We have completed a chapter on classes and objects where we saw that when we typed the name of the instantiated class into our editor and then typed the . (period), the name of the methods and properties appeared. In this chapter we saw some of the methods of the String class, for example, Trim(), ToUpper(), Split(), and Replace(). While we have covered some of the methods, we have not covered them all, and we could investigate many more of the methods and their use. We have also covered different ways to write code in the WriteLine() method, and we have also looked at the newer features of C#, including constant interpolated strings and then constant strings within interpolated strings available from C# 10.

We are making fantastic progress in our programming of C# applications and we should be very proud of our achievements. In finishing this chapter, we have increased our knowledge further and we are advancing to our target.

An illustration of concentric circles with a text below that reads, our target is getting closer. The circles at the center are shaded in green.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.164.195