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 library. 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.

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:

@page
@model Exercise.Pages.ExerciseModel
@{
    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;
}

<p>@quotation</p>

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

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

@page
@model Exercise.Pages.ExerciseModel
@{
    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;
}

<p>@quotation</p>

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

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. Here are examples that call this function:

@page
@model Valuable.Pages.CreatureModel
@{
    string strFirstName  = string.Empty;
    string strMiddleName = string.Empty;
    string strLastName   = string.Empty;
    string strFullName   = string.Empty;

    if (Request.HasFormContentType)
    {
        strFirstName  = Request.Form["txtFirstName"];
        strMiddleName = Request.Form["txtMiddleName"];
        strLastName   = Request.Form["txtLastName"];

        /* 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))
        {
            strFullName = strFirstName;
        }
        else
        {
        if (strMiddleName == "")
            strFullName = string.Concat(strLastName, ", ", strFirstName);
        else
            strFullName  = string.Concat(strLastName, ", ", strFirstName, " ", strMiddleName);
        }
    }
}

<form method="post" style="width: 350px; font-family: Garamond, Georgia, 'Times New Roman', serif;">
    <table class="table">
        <tr>
            <td>First Name:</td>
            <td>@Html.TextBox("txtFirstName", @strFirstName, new { @class = "form-control" })</td>
        </tr>
        <tr>
            <td>Middle Name:</td>
            <td>@Html.TextBox("txtMiddleName", @strMiddleName, new { @class = "form-control" })</td>
        </tr>
        <tr>
            <td>Last Name:</td>
            <td>@Html.TextBox("txtLastName", @strLastName, new { @class = "form-control" })</td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td><input type="submit" name="btnSubmit" value="Analyze Password" /></td>
        </tr>
    </table>

    <p>Full Name: @strFullName</p>
</form>

Here are examples of using the webpage:

Concatenating Some Strings

Concatenating Some Strings

Concatenating Some Strings

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:

@{
    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";
}

<p>@quote</p>

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
.

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.

String Interpolation

As we have seen in previous lessons, 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 is an example:

@page
@model Exercise.Pages.ExerciseModel
@{
    var employeeNumber = "359-486";
    string firstName = "Claire";
    dynamic lastName = "Simmons";

    string identification = $"{employeeNumber}: {lastName}, {firstName}";
}

<p>@identification, </p>

This would produce:

359-486: Simmons, Claire

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:

@page
@model Valuable.Pages.ArraysModel
@{
    (int emplNumber, string firstName, string lastName, double salary) employee = (284_928, "Paul-Simon", "Ndongo", 73_866);

    string strFullName = $"{employee.lastName}" + ", " + $"{employee.firstName}";
        
}

<pre>=================================
Employee #:    @(employee.emplNumber)
Full Name:     @strFullName
Yearly Salary: @(employee.salary)
=================================</pre>

This would produce:

=================================
Employee #:    284928
Full Name:     Ndongo, Paul-Simon
Yearly Salary: 73866
=================================

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

@page
@model Valuable.Pages.ArraysModel
@using static System.Console
@{
    var staff = (emplNumber: 284928, "Paul-Simon", lastName: "Ndongo", 73866, fullTime: true);

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

This would produce:

Employee Record
---------------------------------------
Employee #:         284928
Full Name:          Paul-Simon Ndongo
Yearly Salary:      73866
Employed Full-Time: True
=======================================

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. Here are examples:

@page
@model Valuable.Pages.CreatureModel
@using static System.Console
@{
    string strFirstName  = string.Empty;
    string strMiddleName = string.Empty;
    string strLastName   = string.Empty;
    string strFullName   = string.Empty;
    string strUsername = string.Empty;

    if (Request.HasFormContentType)
    {
        strFirstName  = Request.Form["txtFirstName"];
        strMiddleName = Request.Form["txtMiddleName"];
        strLastName   = Request.Form["txtLastName"];

        /* 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))
        {
            strFullName = strFirstName;
        }
        else
        {
        if (strMiddleName == "")
            strFullName = string.Concat(strLastName, ", ", strFirstName);
        else
            strFullName  = 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. */
            strUsername = $"{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. */
           strUsername = $"{strFirstName.Substring(0, 1)}{strMiddleName.Substring(0, 1)}{strLastName}".ToLower();
        }
    }
}

<form method="post" style="width: 350px; font-family: Garamond, Georgia, 'Times New Roman', serif;">
    <table class="table">
        <tr>
            <td>First Name:</td>
            <td>@Html.TextBox("txtFirstName", @strFirstName, new { @class = "form-control" })</td>
        </tr>
        <tr>
            <td>Middle Name:</td>
            <td>@Html.TextBox("txtMiddleName", @strMiddleName, new { @class = "form-control" })</td>
        </tr>
        <tr>
            <td>Last Name:</td>
            <td>@Html.TextBox("txtLastName", @strLastName, new { @class = "form-control" })</td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td><input type="submit" name="btnSubmit" value="Create Account" /></td>
        </tr>
    </table>
    <table class="table">
        <tr>
            <td>Full Name:</td>
            <td>@Html.TextBox("txtFullName", @strFullName, new { @class = "form-control" })</td>
        </tr>
        <tr>
            <td>Username:</td>
            <td>@Html.TextBox("txtUsername", @strUsername, new { @class = "form-control" })</td>
        </tr>
    </table>
</form>

Here are examples of using the webpage:

Sub-Strings

Sub-Strings

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.

Building a String

Introduction

We have mentioned that the string type is immutable. To give the ability to work on mutable strings, the .NET library provides a sealed class named StringBuilder. This class is defined in the System.Text namespace.

Both the String and the StringBuilder classes are used to build strings, but they do it differently and behave differently. In reality, the String and the StringBuilder classes have similarities and differences. These characteristics are demonstrated in the way a string is built and used in each of the classes.

An Object to Build a String

To build a string, if you are writing your code in a class, you can include a using System.Text line in the top section of your document. Then, you can declare a StringBuilder variable.

To let you start building a string, the StringBuilder class is equipped with various constructors. If you want to work from scratch, use its default constructor. Here is an example:

@using System.Text

@{
    StringBuilder thoughts = new StringBuilder();
}

To let you work from a primary string, the class is equipped with a constructor that takes a string as argument. Its syntax is:

public StringBuilder(string value);

Here is an example of using this method to start building a string:

@using System.Text

@functions{
    public class Study
    {
        public StringBuilder Sociology;

        public Study()
        {
            Sociology = new StringBuilder("Human Interactions");
        }
    }
}

Primary Operations on String Building

Adding a String to a Builder

The primary operation to start a string consists of adding a character or a word to it. To support this operation, the StringBuilder class is equipped with an overloaded method named Append. This method has a version for every primitive type. For example, the version used to add an integer to a string uses the following syntax:

public StringBuilder Append(int value);

The version of the StringBuilder.Append() method used to add a string uses the following syntax:

public StringBuilder Append(string value);

The primary operation to start a string consists of adding a character or a word to it. To support this operation, the StringBuilder class is equipped with an overloaded method named Append. This method has a version for every primitive type. For example, the version to add a string uses the following syntax:

public StringBuilder Append(string value);

When you call the StringBuilder.Append() method, if the object is empty, such as if this is the first time you are calling the method on a variable declared using the default constructor, the argument would constitute the primary string of the variable. Based on this, here is an example of starting building a string:

@using System.Text
@{
    StringBuilder thoughts = new StringBuilder();

    thoughts.Append("I think NFL Football players are probaly no different than lawyers in terms of attacking opponents and then after the event, shaking hands and going back to a civil normal life.");
}

The Value of a Built String

When you declare a StringBuilder variable, you get a String object. As a result, you can use a StringBuilder object where you would use a string value. For example, you can display its value in a console window. Here is an example:

@page
@model Valuable.Pages.CreatureModel
@using System.Text
@{
    StringBuilder thought = new StringBuilder();

    thought.Append("I think NFL Football players are probaly no different than lawyers in terms of attacking opponents and then after the event, shaking hands and going back to a civil normal life.");
}

<p>@thought</p>
<p>====================================<p>

This would produce:

I think NFL Football players are probaly no different than lawyers in terms of a
ttacking opponents and then after the event, shaking hands and going back to a c
ivil normal life.
====================================

Of course, you can also access a StringBuilder object declared in a class.

Converting a Built String to a String

One of the similarities between the String and the StringBuilder classes is that each of them holds a sequence of characters. In most cases, each of them can be used interchangeable, but not always. This depends on the context the variable of the String or the StringBuilder class is used. In the above example, we saw that the Console.Write() or the Console.WriteLine() method can be used to display the value of a StringBuilder variable, but a message box or a text box cannot display the value of a StringBuilder variable. Why?

Remember that both the String and the StringBuilder variable hold a sequence or array of characters. To support this, the overloaded Console.Write() and Console.WriteLine() methods have a version as follows:

public static void Write (char[] buffer);
public static void WriteLine (char[] buffer);

This means that, whether you pass a string or a StringBuilder value to a Console.Write() or Console.WriteLine(), these methods are equipped to handle and display a sequence or array of characters. If you ask another property or method to simply use a StringBuilder value, if that property or method is not directly equipped to handle a StringBuilder object, the property or method would not know what to do. To address this issue, the StringBuilder class overrides the ToString() method:

public override string ToString();

As a reault, whenever you need to use a StringBuilder value where you need a string, you can first convert the value to a string. Here are two examples:

@page
@model Valuable.Pages.CreatureModel
@using System.Text
@{
    StringBuilder thought = new StringBuilder();

    thought.Append("I think NFL Football players are probaly no different than lawyers in terms of attacking opponents and then after the event, shaking hands and going back to a civil normal life.");
}

<p>Thought: @thought.ToString()</p>
<p>====================================<p>

This would produce:

Thought: I think NFL Football players are probaly no different than lawyers in terms of attacking opponents and then after the event, shaking hands and going back to a civil normal life.

As an alternative, you may want to create a string using some sections of a StringBuilder value. To support this, the StringBuilder class provides another version of the ToString() method. Its syntax is:

public string ToString (int startIndex, int length);

Adding Strings to a Builder

To add more than one string to a StringBuilder object, you can call the StringBuilder.Append() method. Here is an example:

@page
@model Valuable.Pages.CreatureModel
@using System.Text
@using static System.Console
@{
    StringBuilder thought = new StringBuilder();

    thought.Append("I think NFL Football players are probaly no different than " +
                   "lawyers in terms of attacking opponents and then after the " +
                   "event, shaking hands and going back to a civil normal life.");

    thought.Append(" - Dr. Robert Huizenga");

    WriteLine(thought.ToString());
}

This would produce:

I think NFL Football players are probaly no different than lawyers in terms of attacking opponents and then after the event, shaking hands and going back to a civil normal life. - Dr. Robert Huizenga

In the same way, you can keep calling the StringBuilder.Append() to add more strings, each call with the desired value. Here are examples:

@page
@model Valuable.Pages.CreatureModel
@using System.Text
@using static System.Console
@{
    StringBuilder fields = new StringBuilder("Information Theory");

    fields.Append("\n");
    fields.Append("Databases");
    fields.Append("\n");
    fields.Append("Articfial Intelligence");
    fields.Append("\n");
    fields.Append("Computer Networking");
    fields.Append("\n");
    fields.Append("Graphics and Visualization");
    fields.Append("\n");
    fields.Append("Computer Security");
    fields.Append("\n");
    fields.Append("Cryptography");
    fields.Append("\n");
    fields.Append("Software Engineering");

    WriteLine(fields.ToString());
}

This would produce:

Information Theory
Databases
Articfial Intelligence
Computer Networking
Graphics and Visualization
Computer Security
Cryptography
Software Engineering

Remember that the StringBuilder class provides an Append() method for every primitive type. This allows you to add all types of values to a StringBuilder object. You can also pass variables, fields, or properties that hold values. Here are examples:

@page
@model Valuable.Pages.CreatureModel
@using System.Text
@using static System.Console
@{
    IPolyhedron poly = new Tetrahedron(4, 6, 4);
    StringBuilder description = new StringBuilder();

    description.Append("A ");
    // Adding a string
    description.Append(poly.Name);
    description.Append(" is a polyhedron with ");
    // Adding an integer
    description.Append(poly.Faces);
    description.Append(" faces, ");
    description.Append(poly.Edges);
    description.Append(" edges, and ");
    description.Append(poly.Vertices);
    description.Append(" vertices. The formula to calculate its surface area is Edge * Edge * ");
    // Adding a double-precision floating-point number
    description.Append(poly.FactorArea);
    description.Append(" and its volume is approximately Edge * Edge * Edge * ");
    description.Append(poly.FactorVolume);

    WriteLine(description.ToString());
    WriteLine("--------------------------------------------------------------------------------");
    poly = new Octahedron(8, 12, 6);

    description = new StringBuilder();

    description.Append("An ");
    // Adding a string
    description.Append(poly.Name);
    description.Append(" is a polyhedron with ");
    // Adding an integer
    description.Append(poly.Faces);
    description.Append(" faces, ");
    description.Append(poly.Edges);
    description.Append(" edges, and ");
    description.Append(poly.Vertices);
    description.Append(" vertices. The formula to calculate its surface area is Edge * Edge * ");
    // Adding a double-precision floating-point number
    description.Append(poly.FactorArea);
    description.Append(" and its volume is approximately Edge * Edge * Edge * ");
    description.Append(poly.FactorVolume);

    WriteLine(description.ToString());
    WriteLine("================================================================================");
}

@functions{
    public interface IPolyhedron
    {
        string Name         { get; }
        double FactorArea   { get; }
        double FactorVolume { get; }
        int Faces           { get; }
        int Edges           { get; }
        int Vertices        { get; }
    }

    public class Tetrahedron : IPolyhedron
    {
        public double FactorArea   => 1.732051;
        public double FactorVolume => 0.117851;
        public string Name         => "Tetrahedron";

        public int    Faces    { get;  }
        public int    Edges    { get;  }
        public int    Vertices { get;  }
        public double Edge     { get; set; }

        public Tetrahedron(int faces, int edges, int vertices)
        {
            Faces    = faces;
            Edges    = edges;
            Vertices = vertices;
        }
    }

    public class Octahedron : IPolyhedron
    {
        public int    Faces    { get;      }
        public int    Edges    { get;      }
        public int    Vertices { get;      }
        public double Edge     { get; set; }

        public double FactorArea   => 3.464102;
        public double FactorVolume => 0.471405;
        public string Name         => "Octahedron";

        public Octahedron(int faces, int edges, int vertices)
        {
            Faces = faces;
            Edges = edges;
            Vertices = vertices;
        }
    }
}

This would produce:

A Tetrahedron is a polyhedron with 4 faces, 6 edges, and 4 vertices. The formula to calculate its surface area is Edge * Edge * 1.732051 and its volume is approximately Edge * Edge * Edge * 0.117851
-------------------------------------------------------------------------------
An Octahedron is a polyhedron with 8 faces, 12 edges, and 6 vertices. The formula to calculate its surface area is Edge * Edge * 3.464102 and its volume is approximately Edge * Edge * Edge * 0.471405
================================================================================

Inserting a String

The StringBuilder.Append() method adds a string at the end of the existing string of the variable and produces a new string. The new string is considered a group (or array) of characters. This means that the produced string is not treated as a group of strings but as an array of characters. Each character or symbol occupies a specific position which is its index. The first character is positioned at index 0. The second character is positioned at index 1, and so on.

To let you add a character or string to the beginning, or to insert a character or a string at the beginning of the existing string, the StringBuilder class is equipped with an overloaded method named Insert. Each version of this method takes two arguments. The version used to insert a double-precision number uses the following syntax:

public StringBuilder Insert(int index, double value);

The version used to insert a string uses the following syntax:

public StringBuilder Insert(int index, string value);

The first argument is the index where you want the new value. The characters after that position would be pushed to the right. Here is an example:

@page
@model Valuable.Pages.CreatureModel
@using System.Text
@using static System.Console
@{StringBuilder fields = new StringBuilder("Information Theory");

    fields.Append(", ");
    fields.Append("Databases");
    fields.Append(", ");
    fields.Append("Articfial Intelligence");
    fields.Append(", ");
    fields.Append("Computer Networking");
    fields.Append(", ");
    fields.Append("Graphics and Visualization");
    fields.Append(", ");
    fields.Append("Computer Security");
    fields.Append(", ");
    fields.Append("Cryptography");
    fields.Append(", and ");
    fields.Append("Software Engineering.");

    fields.Insert(0, "Computational Science, ");

    WriteLine(fields.ToString());

    fields.Insert(54, "Distributed Systems, ");
    WriteLine("-----------------------------------------------------------------------------");

    WriteLine(fields.ToString());

    WriteLine("=============================================================================");
}

<p>@fields.ToString()</p>

@{
    fields.Insert(54, "Distributed Systems, ");
}

<p>-----------------------------------------------------------------------------</p>

<p>@fields.ToString()</p>

<p>=============================================================================</p>

This would produce:

Computational Science, Information Theory, Databases, Articfial Intelligence, Computer Networking, Graphics and Visualization, Computer Security, Cryptography, and Software Engineering.
-----------------------------------------------------------------------------
Computational Science, Information Theory, Databases, Distributed Systems, Articfial Intelligence, Computer Networking, Graphics and Visualization, Computer Security, Cryptography, and Software Engineering.
=============================================================================

Encoding and Decoding Text

Introduction

An application may have to deal with various types of values from different documents or communication means. The documents primarily contain text and such text can include various types of characters. A document may include some special symbols. Examples are < (the less than symbol), > (the greater than symbol), ' (the single quote), " (the double-quote), etc. Sometimes, those same symbols may be included in the text that must be sent. In some cases, you may want to publish some characters from various languages such as Greek, German, etc. If you don't do a good job, you may get corrupted or unpredictable results. To faithfully produce a document, you can make your application use some algorithms to analyze, check, and convert the characters somehow, or you can give your own special instructions to the application. You have various options.

Encoding Text

The .NET library provides various techniques to manipulate characters so they can be appropriately displayed in any application. This is mostly supported in the System.Text namespace. This namespace includes a class named Encoder. This class considers one character or an array of characters provided in Unicode format. The class would convert the character(s) in an appropriate format readable to the intended audience.

The primary class used to encode a character is named Encoding. This is an abstract class that receives a character as a byte type. The class analyzes such a character and produces the necessary result. Encoding is an abstract class. A class derived from it would do the actual job. Because human languages use different ways to represent their particular characters, the .NET library provides various classes for encoding.

Latin-based languages such as English primarily use 8 bits to represent their characters. To support this format, the .NET library provides a class named UTF8Encoding. This class is derived from Encoding.

To prepare to encode a character, declare a variable of type UTF8Encoding. The class is equipped with three constructors, including the default. Therefore, to start encoding, you can declare a UTF8Encoding variable using its default constructor. If you are working in a class, you can include the namespace in the top section of the document. Here is an example:

using System.Text;

public class Correspondance
{
    UTF8Encoding u8e = new UTF8Encoding();
}

To let you specify the character or the string to be encoded, the Encoding class is equipped with an overloaded method named GetBytes that its child classes inherit. This method provides versions that take a string, an array of characters, a sub-string from an existing string delimited by a starting index, and many oters. The version that takes a string uses the following syntax:

public virtual byte[] GetBytes(string s);

This method considers every one of the characters passed through the argument. It converts each character to its ASCII equivalent and produces an array that contains the ASCII numbers of the characters as items. Here is an example:

@page
@model Valuable.Pages.CreatureModel
@using System.Text
@{
        UTF8Encoding u8e = new UTF8Encoding();

        byte[] characters = u8e.GetBytes("Copyright &copy;, 2021");
}
        
@for(int i = 0; i<characters.Length - 1; i++)
{
    <p>Character: @characters[i])</p>
}
            
<p>=======================================================</p>

This would produce:

Character: 67
Character: 111
Character: 112
Character: 121
Character: 114
Character: 105
Character: 103
Character: 104
Character: 116
Character: 32
Character: 38
Character: 99
Character: 111
Character: 112
Character: 121
Character: 59
Character: 44
Character: 32
Character: 50
Character: 48
Character: 50
=======================================================

Previous Copyright © 2001-2022, FunctionX Thursday 14 October 2021 Next