Fundamentals of Characters

Introduction

To recognize the symbols (letters, digits, special characters, etc) used in an application, the C# language provides a data type named char. The char data type is identified in the .NET library by a structure named Char. This structure is represented by a 16-bit value.

To declare a variable that can hold one character, a letter, or a symbol, use the char data type or the Char structure. To initialize the variable, include its value between two single-quotes. Here are examples:

@{
    char gender = 'm';
    char moneySymbol = '$';
    char multiplication = '*';
    char numberOne = '1';
}

You can also use the var or the dynamic keyword if you are initializing the variable.

Passing a Character to a Function or Method

Like a normal value, a character can be passed to a function or method as argument. Here is an example:

@functions{
    void GetEmploymentStatus(char s)
    {
        switch (s)
        {
            case 'p':
                EmploymentStatus = "Part-Time";
                break;
            case 'f':
                EmploymentStatus = "Full-Time";
                break;
            case 'c':
                EmploymentStatus = "Contractor";
                break;
            default:
                EmploymentStatus = "Unknown";
                break;
        }
    }
}

When calling the function or method, pass a value for the argument in single-quotes. Here is an example:

@page
@model Exercises.Pages.ExerciseModel
@{
    string result = GetEmploymentStatus('f');
}
    
@functions{
    string GetEmploymentStatus(char s)
    {
        string employmentStatus;

        switch (s)
        {
            case 'p':
                employmentStatus = "Part-Time";
                break;
            case 'f':
                employmentStatus = "Full-Time";
                break;
            case 'c':
                employmentStatus = "Contractor";
                break;
            default:
                employmentStatus = "Unknown";
                break;
        }

        return employmentStatus;
    }
}

<pre>Employment Status: @result

===============================</pre>

This would produce:

Employment Status: Full-Time
===============================

Returning a Character From a Function or Method

You can create a function or method that returns a character. To do this, when creating the method, on the left of its name, specify the return type as char. In the body of the method, before the closing curly bracket. return a character. Here is an example:

@functions{
    public char SetEmploymentStatus()
    {
        char s = 's';
        return s;
    }
}

When calling the method, you can assign its return value in a character.

Case Conversions for Characters

Converting a Character to Lowercase

To let you convert a character to lowercase, the Char structure is equipped with the ToLower() method. It is overloaded with two versions. One of the versions uses the following syntax:

public static char ToLower(char c)

This method follows the same logic as its ToUpper() counterpart. If the character is not an alphabetic character, it would be kept "as-is". If the character is an uppercase alphabetic character, it would be converted to lowercase. If it is in lowercase, it would not be converted.

Converting a Character to Uppercase

The English language uses two character representations: lowercase and uppercase. The characters in lowercase are: a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, and z. The equivalent characters in uppercase are represented as A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, and Z. Characters used for counting are called numeric characters; each one of them is called a digit. They are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. There are other characters used to represent things in computer applications, mathematics, and others. Some of these characters, also called symbols are ~ , ! @ # $ % ^ & * ( ) _ + { } ` | = [ ] \ : " ; ' < > ? , . / These characters are used for various reasons and under different circumstances. For example, some of them are used as operators in mathematics or in computer programming. Regardless of whether a character is easily identifiable or not, all these symbols are character types and can be declared using the char data type followed by a name.

An alphabetic character, for any reason judged necessary, can be converted from one case to another. The other characters, non-alphabetic symbols, and the numbers, do not have a case and therefore cannot be converted in cases.

To let you convert a character from lowercase to uppercase, the Char structure is equipped with a method named ToUpper(). It is overloaded with two versions. One of the versions of this method uses the following syntax:

public static char ToUpper(char c)

This method takes a character as argument. If the character is already in uppercase, it would not change. If the character is a lowercase alphabetic character, it would be converted to uppercase. If the character is not an alphabetic character, it would be kept "as-is".

Escape Sequences

An escape sequence is a type of character, usually non-readable, that the compiler must use for some operation, such as using a particular way to display a string. The available escape sequences are:

Escape Sequence Name Description
\a Bell (alert) Makes a sound from the computer
\b Backspace Takes the cursor back
\t Horizontal Tab Takes the cursor to the next tab stop
\n New line Takes the cursor to the beginning of the next line
\v Vertical Tab Performs a vertical tab
\f Form feed  
\r Carriage return Causes a carriage return
\" Double Quote Displays a quotation mark (")
\' Apostrophe Displays an apostrophe (')
\? Question mark Displays a question mark
\\ Backslash Displays a backslash (\)
\0 Null Displays a null character

To use an escape sequence, you can also first declare a char variable and initialize it with the desired escape sequence in single-quotes.

Fundamentals of Strings

Introduction

A string is one or a group of symbols. These symbols can also be referred to as characters; those we introduced in the previous sections. Therefore, a string is one or a series of characters.

To support strings, the .NET library provides a class named String. This class is defined in the C# language as the string data type. Therefore, to create a string, you can declare a variable of type string or String. You can also use the dynamic keyword to declare the variable. Here are examples:

@{
    string firstName;
    dynamic lastName;
}

You can also use the var keyword to declare a string variable. In this case, you must initialize the variable.

A String as an Array of Characters

A string is a group, or an array, of characters. After declaring and initializing a string, it is considered an array of values where each character occupies a specific position. The positions are numbered so that the most left character of the string occupies index 0; the second character is at index 1, and so on.

To support this idea of an array of characters, the String class is equipped with a numbered (called indexed) property named Chars. This is also how you can retrieve the character at a specific index in the string, using the [] operator of arrays. Here is an example:

@{
    var gender = "Female";
    var gdr = gender[2];
}

You can access the Length property to know the number of characters in a string.

Once (and because) a string is considered a collection of items, you can use the foreach operator to access each member of the collection. Here is an example:

@page
@model Exercises.Pages.ExerciseModel
@{
    string gender = "Female";
}

<p>Gender: @gender</p>
<p>-------------------------------</p>

<h4>Individual Characters</h4>

@foreach(char c in gender)
{
    <p>Character: @c</p>
}

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

This would produce:

Gender: Female
-------------------------------
Individual Characters
Character: F
Character: e
Character: m
Character: a
Character: l
Character: e
===============================

Categories of Characters

As far as computers or operating systems are concerned, every readable or non-readable symbol used in an application is a character. All those symbols are considered objects of type char. The Char structure can recognize every one of them. In fact, the Char structure makes the symbols into various categories.

An alphabetical letter is a readable character recognized by a human language. To let you find out whether a character is a letter, the Char structure is equipped with a static method named IsLetter. It is overloaded with two versions. A digit is a symbol used in a number. It can be 0, 1, 2, 3, 4, 5, 6, 7, 8, or 9. To let you find out whether a character is a digit, the Char structure is equipped with the IsDigit() static method that is overloaded with two versions. In the same way, the Char structure provides various methods to test the category of characters being used. All these methods are static and they are given in two versions. Each has a version that takes one argument as a character. If the argument is the type sought, the method returns true. Otherwise it returns false. The methods are:

Method Returns true if the argument is
IsLetter(char c) A letter
IsLower(char c) A lowercase letter
IsUpper(char c) An uppercase letter
IsDigit(char c) A digit
IsNumber(char c) A digit or any other type of number
IsLetterOrDigit(char c) A letter or a digit
IsControl(char c) A control character (Ctrl, Shift, Enter, Del, Ins, etc)
IsPunctuation(char c) A punctuation such as , . - ! ? ' " ( ) | # \ / % & * > @ < » «
IsSymbol(char c) A symbol such as | + ¢ ¤ ± £ = ^ ¨ $
IsWhiteSpace(char c) An empty space such as created by pressing the SPACE bar
IsSeparator(char c) An empty space or the end of a line

Here are examples of calling these methods:

@page
@model Exercises.Pages.ExerciseModel
@{

}

<pre>====================================
Proposition               Conclusion
====================================
 q is a Letter               @Char.IsLetter('q')
------------------------------------
 a is a lowercase letter     @Char.IsLower('a')
------------------------------------
 W is an uppercase letter    @Char.IsUpper('W')
------------------------------------
 1 is a digit                @Char.IsDigit('1')
------------------------------------
 w is a letter or a digit    @Char.IsLetterOrDigit('w')
------------------------------------
 3 is a letter or a digit    @Char.IsLetterOrDigit('w')
------------------------------------
 0 is a number               @Char.IsNumber('0')
------------------------------------
 _ is a punctuation mark     @Char.IsPunctuation('_')
------------------------------------
 # is a punctuation mark     @Char.IsPunctuation('#')
------------------------------------
 \\ is a punctuation mark    @Char.IsPunctuation('\\')
------------------------------------
  is a white space           @Char.IsWhiteSpace(' ')
------------------------------------
  is a separator             @Char.IsSeparator(' ')
------------------------------------
  + is a symbol              @Char.IsSymbol('+')
====================================</pre>

This would produce:

====================================
Proposition               Conclusion
====================================
 q is a Letter               True
------------------------------------
 a is a lowercase letter     True
------------------------------------
 W is an uppercase letter    True
------------------------------------
 1 is a digit                True
------------------------------------
 w is a letter or a digit    True
------------------------------------
 3 is a letter or a digit    True
------------------------------------
 0 is a number               True
------------------------------------
 _ is a punctuation mark     True
------------------------------------
 # is a punctuation mark     True
------------------------------------
 \\ is a punctuation mark    True
------------------------------------
  is a white space           True
------------------------------------
  is a separator             True
------------------------------------
  + is a symbol              True
====================================

You can apply a conditional statement to a method to find out what character is at a certain position.

An Empty String

A string is referred to as empty if it contains no characters at all. To create such a string, you can declare a string or String variable and initialize it with empty double-quotes. Here is an example:

string empty = "";

To support the ability to create an empty string, the String class is equipped with a static field named Empty:

public static readonly string Empty

The String.Empty field allows you to initialize a string variable with an empty space or to reset a string to an empty value. Here are examples:

@{
    string firstName = string.Empty;
    var middleName = string.Empty;
    dynamic lastName = string.Empty;
}

Converting a Value or an Object to a String

To allow you to convert any value or object to a string, the object data type (that is, its equivalent Object class) is equipped with a method named ToString Most classes override this method. If you want a particular implementation of this method for your class, you must override it.

The Length of a String

The length of a string, also referred to as its size, is the number of symbols or characters it contains. To let you get this information, The String class is equipped with a property named Length. Here is an example of using it:

@page
@model Exercise.Pages.ExerciseModel
@{
    string gender = "Female";
}

<p>@gender contains @gender.Length characters</p>

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

This would produce:

Female contains 6 characters
===============================

Once you have the string.Length value, you can use it as you see fit. For example, that value can assist you in calculations related to a string as an array of characters. Here is an example:

@page
@model Valuable.Pages.AccountValidationModel
@{
    int length    = 0;
    int digits    = 0, symbols = 0;
    int lowercase = 0, uppercase = 0;

    string strPassword = "", strConfirm = "";

    if (Request.HasFormContentType)
    {
        strPassword = Request.Form["txtNewPassword"];
        strConfirm = Request.Form["txtConfirmPassword"];

        length = strPassword.Length;

        for (int i = 0; i < length; i++)
        {
            if (Char.IsDigit(strPassword[i]))
                digits++;

            if (Char.IsSymbol(strPassword[i]) || Char.IsPunctuation(strPassword[i]))
                symbols++;

            if (Char.IsLower(strPassword[i]))
                lowercase++;

            if (Char.IsUpper(strPassword[i]))
                uppercase++;
        }
    }
}

<form method="get" style="width: 450px; font-family: Garamond, Georgia, 'Times New Roman', serif;">
    <table class="table">
        <tr>
            <td>New Password:</td>
            <td>@Html.TextBox("txtNewPassword", @strPassword, new { @class = "form-control" })</td>
        </tr>
        <tr>
            <td>Confirm Password:</td>
            <td>@Html.TextBox("txtConfirmPassword", @strConfirm, new { @class = "form-control" })</td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td><input type="submit" name="btnSubmit" value="Analyze Password" /></td>
        </tr>
    </table>

    <table class="table">
        <tr>
            <td>@Html.TextBox("txtCharacters", @length, new { @class = "form-control", style="width: 60px;" })</td>
            <td>Characters</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
        <tr/>
        <tr>
            <td>@Html.TextBox("txtLowercase", @lowercase, new { @class = "form-control", style="width: 60px;" })</td>
            <td>Lowercase Letters</td>
            <td>@Html.TextBox("txtUppercase", @uppercase, new { @class = "form-control", style="width: 60px;" })</td>
            <td>Uppercase Letters</td>
        </tr>
        <tr>
            <td>@Html.TextBox("txtDigits", @digits, new { @class = "form-control", style="width: 60px;" })</td>
            <td>Digits</td>
            <td>@Html.TextBox("txtSymbols", @symbols, new { @class = "form-control", style="width: 60px;" })</td>
            <td>Symbols</td>
        </tr>
    </table>
</form>

Here is an example of running the webpage:/p>

The Length of a String

The Nullity of a String

A Null String

A string is referred to as null if it doesn't (yet) have a(ny) character(s)s. This is usually the case when the string has just been created, or a string variable has just been declared. When you have just declared a variable, to indicate that it is null, assign the null keyword to it. The variable must be declared using the string data type, the String class, or the dynamic keyword. Here are example:

@{
    string firstName = null;
    dynamic lastName = null;
    String homeAddress = null;
}

If you decide to use the var keyword to declare the variable, you cannot assign null to it.

A Null or Empty String

A string is referred to as null if it has lost its character(s). To let you find out whether a string is empty or null, the String class is equipped with a static method named IsNullOrEmpty. Its syntax is:

public static bool IsNullOrEmpty(string value)

When calling this function, pass a string as argument to it. Here is an example:

@page
@model Valuable.Pages.AccountValidationModel
@using static System.Console
@{
    string strPassword = string.Empty;

    if (Request.HasFormContentType)
    {
        strPassword = Request.Form["txtNewPassword"];
        
        if(string.IsNullOrEmpty(strPassword))
        {
            WriteLine("You cannot have a null or empty password. You must provide " +
                      "a valid password.");
            return;
        }
    }
}

<form method="post" style="width: 450px; font-family: Garamond, Georgia, 'Times New Roman', serif;">
    <table class="table">
        <tr>
            <td>New Password:</td>
            <td>@Html.TextBox("txtNewPassword", @strPassword, new { @class = "form-control" })</td>
        </tr>
        <tr>
            <td>Confirm Password:</td>
            <td>@Html.TextBox("txtConfirmPassword", @strConfirm, new { @class = "form-control" })</td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td><input type="submit" name="btnSubmit" value="Analyze Password" /></td>
        </tr>
    </table>
</form>

A String With a White Space

A string contains a white space if it was previously initialized with at least one character and all its characters have been removed or the string was simply initialized with something like the Space bar of the keyboard. Here is an example:

string whiteSpace = "    ";

A Null, Empty, or White-Spaced String

To let you find out whether a string is null or contains a white space, the String class is equipped with a static method named IsNullOrWhiteSpace. Its syntax is:

public static bool IsNullOrWhiteSpace(string value)

Here is an example that calls this function:

@page
@model Valuable.Pages.AccountValidationModel
@using static System.Console
@{
    int length    = 0;
    int digits    = 0, symbols = 0;
    int lowercase = 0, uppercase = 0;

    string strPassword = string.Empty, strConfirm = string.Empty;

    if (Request.HasFormContentType)
    {
        strPassword = Request.Form["txtNewPassword"];
        
        if(string.IsNullOrWhiteSpace(strPassword))
        {
            WriteLine("You cannot have a null or white space password (a password with no character at all). " +
                      "You must create a new password that conforms to this company's password rules.");
            return;
        }
    }
}

<form method="post" style="width: 450px; font-family: Garamond, Georgia, 'Times New Roman', serif;">
    <table class="table">
        <tr>
            <td>New Password:</td>
            <td>@Html.TextBox("txtNewPassword", @strPassword, new { @class = "form-control" })</td>
        </tr>
        <tr>
            <td>Confirm Password:</td>
            <td>@Html.TextBox("txtConfirmPassword", @strConfirm, new { @class = "form-control" })</td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td><input type="submit" name="btnSubmit" value="Analyze Password" /></td>
        </tr>
    </table>
</form>

Comparing Strings

Strings Comparisons

String Equality

The indexed-equivalent characters of two strings can be compared to know whether one is lower or higher than the other. If you are only interested to know whether two strings are equivalent, to assist you with that operation, the string type is equipped with a method named Equals. It is overloaded with various versions. Two versions use the following syntaxes:

public override bool Equals(object obj);
public bool Equals(string value);

When calling one of these versions, use an object object or a string value that calls it. The method takes one argument. The variable that calls the method is compared to the value passed as argument. If both values are the exact same, the method returns true. The comparison is performed considering the case of each character. Here is an example of calling the above second version of the method:

@page
@model Valuable.Pages.AccountValidationModel
@using static System.Console
@{
    int length    = 0;
    int digits    = 0, symbols = 0;
    int lowercase = 0, uppercase = 0;

    string strPassword = string.Empty, strConfirm = string.Empty;

    if (Request.HasFormContentType)
    {
        strPassword = Request.Form["txtNewPassword"];
        strConfirm = Request.Form["txtConfirmPassword"];
        
        if (string.IsNullOrWhiteSpace(strPassword))
        {
            WriteLine("You cannot have a null or white space password (a password with no character at all). " +
                      "You must create a new password that conforms to this company's password rules.");
            return;
        }

        if( strPassword.Equals(strConfirm))
        {
            length = strPassword.Length;
        }
        else
        {
            WriteLine("Your passwords do not match. You must type the same pawword in both text boxes.");
        }
    }
}

<form method="post" style="width: 450px; font-family: Garamond, Georgia, 'Times New Roman', serif;">
    <table class="table">
        <tr>
            <td>New Password:</td>
            <td>@Html.TextBox("txtNewPassword", @strPassword, new { @class = "form-control" })</td>
        </tr>
        <tr>
            <td>Confirm Password:</td>
            <td>@Html.TextBox("txtConfirmPassword", @strConfirm, new { @class = "form-control" })</td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td><input type="submit" name="btnSubmit" value="Analyze Password" /></td>
        </tr>
    </table>
</form>

If you don't want to consider the case of each string, use the following version of the method:

public bool Equals(string value, StringComparison comparisonType);

An alternative to the second syntax is to use a static version of this method whose syntax is:

public static bool Equals(string a, string b);

This method takes two string arguments and compares them. If they are the same, the method returns true. This method considers the cases of the characters. Here is an example:

@page
@model Valuable.Pages.AccountValidationModel
@using static System.Console
@{
    int length    = 0;
    int digits    = 0, symbols = 0;
    int lowercase = 0, uppercase = 0;

    string strPassword = string.Empty, strConfirm = string.Empty;

    if (Request.HasFormContentType)
    {
        strPassword = Request.Form["txtNewPassword"];
        strConfirm = Request.Form["txtConfirmPassword"];

        if (string.IsNullOrWhiteSpace(strPassword))
        {
            WriteLine("You cannot have a null or white space password (a password with no character at all). " +
                      "You must create a new password that conforms to this company's password rules.");
            return;
        }

        if(string.Equals(strPassword, strConfirm))
        {
            length = strPassword.Length;
        }
        else
        {
            WriteLine("Your passwords do not match. You must type the same pawword in both text boxes.");
        }
    }
}

<form method="post" style="width: 450px; font-family: Garamond, Georgia, 'Times New Roman', serif;">
    <table class="table">
        <tr>
            <td>New Password:</td>
            <td>@Html.TextBox("txtNewPassword", @strPassword, new { @class = "form-control" })</td>
        </tr>
        <tr>
            <td>Confirm Password:</td>
            <td>@Html.TextBox("txtConfirmPassword", @strConfirm, new { @class = "form-control" })</td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td><input type="submit" name="btnSubmit" value="Analyze Password" /></td>
        </tr>
    </table>
</form>

If you don't want the cases of the string to be taken into consideration, use the following version of the method:

public static bool Equals(string a,
			  string b,
			  StringComparison comparisonType);

String Integral Comparison

String comparison consists of examining the characters of two strings with a character of one string compared to a character of the other string with both characters at the same positions. To support this operation, the String class (and therefore the string data type) is equipped with a method named Compare(), That method is overloaded with many versions. One of the versions uses the following syntax:

public static int Compare(string String1, string  String2);

This method is declared static and it takes two arguments. The method returns

Here are three examples of calling this method:

@page
@model Valuable.Pages.ArraysModel
@{
    string firstName1 = "Andy";
    string lastName1 = "Stanley";
    string firstName2 = "Charles";
    string lastName2 = "Stanley";
    
    int value1 = string.Compare(firstName1, firstName2);
    int value2 = string.Compare(firstName2, firstName1);
    int value3 = string.Compare(lastName1, lastName2);
}

<p>===========================</p>
<p>@firstName1 compared to @firstName2 produces @value1</p>
<p>@firstName2 compared to @firstName1 produces  @value2</p>
<p>@lastName1 compared to @lastName2 produces @value3</p>
<p>===========================</p>

This would produce:

=============================================
"Andy"    compared to "Charles" produces -1
"Charles" compared to "Andy"    produces  1
"Stanley" compared to "Stanley" produces  0
=============================================

When using this version of the string.Compare() method, the case (upper or lower) of each character is considered. If you don't want to consider this factor, the String class proposes another version of the method. Its syntax is:

public static int Compare(string String1, string String2, bool ignoreCase);

The third argument allows you to ignore the case of the characters when performing the comparison.

String-Case Conversions

Converting a String to Lowercase

To let you convert a string from lowercase to uppercase, the String class is equipped with a method named ToLower. It is overloaded with two versions. One of the versions of this method uses the following syntax:

public string ToLower();

This method considers each character of the string that called it. If the character is already in uppercase, it would not change. If the character is a lowercase alphabetic character, it would be converted to uppercase. If the character is not an alphabetic character, it would be kept "as-is".

Converting a String to Uppercase

To let you convert a string to uppercase, the String class is equipped with a method named ToUpper. This method is overloaded with two versions. The syntax of one of the versions is:

public string ToUpper()

Here is an example:

@page
@model Exercise.Pages.ExerciseModel
@{
    string strFullName = "Alexander Patrick Katts";
    string strUppercase = strFullName.ToUpper();
}

<pre>======================================
Full Name:    @strFullName
In Uppercase: @strUppercase
======================================</pre>

This would produce:

======================================
Full Name:    Alexander Patrick Katts
In Uppercase: ALEXANDER PATRICK KATTS
======================================

Previous Copyright © 2001-2022, FunctionX Friday 26 November 2021 Next