Fundamentals of Characters

Introduction

To recognize the symbols used on a webpage (letters, digits, special characters, etc), the C# language provides a data type named char. The char data type is identified in the .NET Framework by the Char structure, which gets represented with 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.

Practical LearningPractical Learning: Introducing Characters

  1. Save the following picture to your computer:

    Gas Utility Company

  2. Start Microsoft Visual Studio
  3. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  4. In the middle frame of the New Object dialog box, make sure ASP.NET Web Application (.NET Framework) is selected.
    Change the project Name to GasUtilityCompany5
  5. Click OK
  6. In the New ASP.NET Web Application dialog box, in the templates list, click the MVC icon and click OK
  7. In the Solution Explorer, right-click GasUtilityCompany5 -> Add -> New Folder
  8. Type Images as the name of the folder and press Enter
  9. Add the above picture to the Images folder
  10. In the Solution Explorer, right-click Content -> Style Sheet
  11. Type Utilities as the name of the file, and press Enter
  12. Add the following styles to the file:
    body {
        padding-top: 150px;
        background-color: #EEEEEE;
    }
    
    #top-banner {
        top: 0;
        left: 0;
        right: 0;
        width: 100%;
        bottom: auto;
        height: 5.75em;
        position: absolute;
        background-color: #192E46; }
    
    .centralizer {
        margin: auto;
        width: 700px; }
    
    .navbar-inverse {
        background-color: orange;
        border-color: #080808;
    }
    
    .navbar {
        border-top: 5px solid #faf76f;
        border-bottom: 5px solid navy;
    }
    
    .navbar-fixed-top { top: 80px; }
    
    .navbar-inverse .navbar-nav > li > a,
    .navbar-inverse .navbar-nav > li > a:link {
        color: #faf76f;
        background-color: transparent;
    }
    
    .navbar-inverse .navbar-nav > li > a:hover,
    .navbar-inverse .navbar-nav > li > a:focus {
        color: orange;
        background-color: #faf76f;
    }
    
    .body-holder {
        width: 800px;
        margin: auto; }
    
    .col-md-3 {
        padding-top: 10px;
        border-radius: 6px;
        padding-bottom: 10px;
        background-color: #800000;
        border: 1px solid #000000; }
    
    .jumbotron {
        padding-top: 3px;
        border-radius: 10px;
        background-color: #f1ddca;
    }
    
    .jumbotron h1 {
        color: #800000;
        font-size: 43px;
    }
    
    .lead { margin-bottom: 0; }
    
    #bottom-banner {
        left: 0;
        right: 0;
        bottom: 0;
        top: auto;
        width: 100%;
        height: 4.15em;
        position: absolute;
        background-color: #003366;
        border-top: 5pt solid black; }
    
    #copyright {
        color: orange;
        margin-top: 1em;
        font-weight: 600;
        font-size: 1.15em;
        text-align: center;
        line-height: 1.15em;
        font-family: Garamond, Georgia, 'Times New Roman', serif; }
    
    .topic { float: left }
    
    .topic a:link, .topic a:active, .topic a:visited, .topic a:hover {
        height: 32px;
        font-size: 12pt;
        line-height: 26px;
        margin-left: -10px;
        padding-left: 20px;
        text-decoration: none;
        display: inline-block;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
    
    .topic, .topic a:link, .topic a:active,
    .topic a:visited, .topic a:hover { width: 190px }
    
    .topic a:link    { color: #FFFF00 }
    .topic a:active  { color: #CC99FF }
    .topic a:visited { color: #FFCC99 }
    
    .topic a:hover {
        color: #FFCCFF;
        display: inline-block;
        background-color: #ff6a00;
        outline: 1pt solid #CCFF33; }
    
    .small-text      { width: 30px; }
    .left-col        { width: 120px }
    .large           { width: 168px }
    .txtContext      { width: 80px  }
    .left-column     { width: 200px }
    .left-text-boxes { width: 100px }
    .right-label     { width: 145px }
    .horizontal-line { border-bottom: 1px dotted #000000; }
    
    .btnLarge {
        height: 32px;
        width: 400px; }
  13. In the Solution Explorer, right-click Controllers -> Add -> New Scaffolded Item...
  14. In the Add Scaffold dialog box, in the middle frame, click MVC 5 Controller - Empty and click Add
  15. Type to Employees to get EmployeesController
  16. Click Add
  17. Add a method named AccountCreation that follows the same formula as the existing method:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace GasUtilityCompany4.Controllers
    {
        public class EmployeesController : Controller
        {
            // GET: Employees
            public ActionResult Index()
            {
                return View();
            }
    
            // GET: AccountCreation
            public ActionResult AccountCreation()
            {
                return View();
            }
        }
    }
  18. In the Solution Explorer, right-click Controllers -> Add -> Controller...
  19. In the Add Scaffold dialog box, in the middle frame, make sure MVC 5 Controller -Empty is selected and click Add
  20. Type Customers to get CustomersController
  21. Click Add
  22. Add a method named BillPreparation that follows the same formula as the other method:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace GasUtilityCompany4.Controllers
    {
        public class CustomersController : Controller
        {
            // GET: Customers
            public ActionResult Index()
            {
                return View();
            }
    
            // GET: BillPreparation
            public ActionResult BillPreparation()
            {
                return View();
            }
        }
    }
  23. In the Solution Explorer, under Views, right-click Customers -> Add -> View...
  24. Type BillPreparation as the View Name
  25. Click Add
  26. To create a form, change the document as follows:
    @{
        ViewBag.Title = "Customer Invoice Preparation";
    }
    
    <h2 class="text-center">Gas Utility Company</h2>
    <h3 class="text-center">Customer Bill Preparation</h3>
    
    <div class="horizontal-line"></div>
    
    @{
        double CCFTotal = 0;
        double amountDue = 0;
        double localTaxes = 0;
        double stateTaxes = 0;
        double totalTherms = 0;
        double over50Therms = 0;
        double first50Therms = 0;
        double deliveryTotal = 0;
        double meterReadingEnd = 0;
        double meterReadingStart = 0;
        int    invoiceNumber = 100001;
        double environmentalCharges = 0;
        double transportationCharges = 0;
        double distributionAdjustment = 0;
    
        if (IsPost)
        {
    
        }
    }
    
    @using (Html.BeginForm())
    {
        <table>
            <tr>
                <td class="left-column">Invoice #:</td>
                <td class="left-text-boxes">@Html.TextBox("txtInvoiceNumber", @invoiceNumber, new { @class = "txtContext" })</td>
                <td class="right-label">&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>Counter Reading Start:</td>
                <td>@Html.TextBox("txtMeterReadingStart", @meterReadingStart, new { @class = "txtContext" })</td>
                <td>Counter Reading End:</td>
                <td>@Html.TextBox("txtMeterReadingEnd", @meterReadingEnd, new { @class = "txtContext" })</td>
            </tr>
        </table>
        <p class="text-center"><input type="submit" class="btnLarge" value="Prepare Invoice" name="btnPrepareInvoice" /></p>
        <div class="horizontal-line"></div>
        <table>
            <tr>
                <td class="left-column">CCF Total:</td>
                <td class="left-text-boxes">@Html.TextBox("txtCCFTotal", @CCFTotal.ToString("F"), new { @class = "txtContext" })</td>
                <td class="right-label">Total Therms:</td>
                <td>@Html.TextBox("txtTotalTherms", @totalTherms.ToString("F"), new { @class="txtContext" })</td>
            </tr>
            <tr>
                <td>Transportation Charges:</td>
                <td>@Html.TextBox("txtTransportationCharges", @transportationCharges.ToString("F"), new { @class = "txtContext" })</td>
                <td>Delivery Total:</td>
                <td>@Html.TextBox("txtDeliveryTotal", @deliveryTotal.ToString("F"), new { @class = "txtContext" })</td>
            </tr>
        </table>
        <div class="horizontal-line"></div>
        <table>
            <tr>
                <td class="left-column">Ditribution Adjust (*0.13086):</td>
                <td class="left-text-boxes">@Html.TextBox("txtDitributionAdjustment", @distributionAdjustment.ToString("F"), new { @class = "txtContext" })</td>
                <td class="right-label">Environment Charges:</td>
                <td>@Html.TextBox("txtEnvironmentCharges", @environmentalCharges.ToString("F"), new { @class = "txtContext" })</td>
            </tr>
            <tr>
                <td>First 50 Therms (*0.5269):</td>
                <td>@Html.TextBox("txtFirst50Therms", @first50Therms.ToString("F"), new { @class = "txtContext" })</td>
                <td>Local/County Taxess:</td>
                <td>@Html.TextBox("txtLocalTaxes", @localTaxes.ToString("F"), new { @class = "txtContext" })</td>
            </tr>
            <tr>
                <td>Over 50 Therms (*0.4995):</td>
                <td>@Html.TextBox("txtOver50Therms", @over50Therms.ToString("F"), new { @class = "txtContext" })</td>
                <td>State Taxess:</td>
                <td>@Html.TextBox("txtStateTaxes", @stateTaxes.ToString("F"), new { @class = "txtContext" })</td>
            </tr>
        </table>
        <div class="horizontal-line"></div>
        <table>
            <tr>
                <td class="left-column">&nbsp;</td>
                <td class="left-text-boxes">&nbsp;</td>
                <td class="right-label">Amount Due:</td>
                <td>@Html.TextBox("txtAmountDue", @amountDue.ToString("F"), new { @class = "txtContext" })</td>
            </tr>
        </table>
    }
  27. In the Solution Explorer, under Views, right-click Customers -> Add -> View...
  28. Type Index as the View Name
  29. Click Add
  30. To create a from, change the document as follows:
    @{
        ViewBag.Title = "Customers";
    }
    
    <h2>Gas Utility Comnpany - Customers</h2>
    
    <p>@Html.ActionLink("Customer Invoice Preparation", "BillPreparation")</p>
  31. In the Solution Explorer, under Views, right-click Employees -> Add -> View...
  32. Type AccountCreation as the View Name
  33. Click Add
  34. To create a form, change the document as follows:
    @{
        ViewBag.Title = "Employee Account Creation";
    }
    
    <h2 class="text-center">Employee Account Creation</h2>
    
    <div class="horizontal-line"></div>
    
    @{
        int length = 0;
        int digits = 0;
        int symbols = 0;
        int lowercase = 0;
        int uppercase = 0;
    
        if (IsPost)
        {
     
        }
    }
    
    @using (Html.BeginForm())
    {
        <table>
            <tr>
                <td class="left-col">First Name:</td>
                <td>@Html.TextBox("txtFirstName", "")</td>
            </tr>
            <tr>
                <td>Middle Name:</td>
                <td>@Html.TextBox("txtMiddleName", "")</td>
            </tr>
            <tr>
                <td>Last Name:</td>
                <td>@Html.TextBox("txtLastName", "")</td>
            </tr>
            <tr>
                <td>Username:</td>
                <td></td>
            </tr>
        </table>
        <div class="horizontal-line"></div>
        <table>
            <tr>
                <td class="left-col">New Password:</td>
                <td>@Html.TextBox("txtNewPassword", "")</td>
                <td>@Html.TextBox("txtCharacters", @length, new { @class = "small-text" }) Characters</td>
            </tr>
            <tr>
                <td>Confirm Password:</td>
                <td>@Html.TextBox("txtConfirmPassword", "")</td>
                <td>&nbsp;</td>
            </tr>
        </table>
        <table>
            <tr>
                <td class="left-col">&nbsp;</td>
                <td class="large">@Html.TextBox("txtLowercase", @lowercase, new { @class = "small-text" }) Lowercase Letters</td>
                <td>@Html.TextBox("txtUppercase", @uppercase, new { @class = "small-text" }) Uppercase Letters</td>
            </tr>
            <tr>
                <td class="left-col">&nbsp;</td>
                <td>@Html.TextBox("txtDigits", @digits, new { @class = "small-text" }) Digits</td>
                <td>@Html.TextBox("txtSymbols", @symbols, new { @class = "small-text" }) Symbols</td>
            </tr>
        </table>
        <div class="horizontal-line"></div>
        <p class="text-center"><input type="submit" name="btnSubmit" value="Submit" class="btnLarge" /></p>
    }
  35. In the Solution Explorer, under Views, right-click Employees -> Add -> View...
  36. Type Index as the View Name
  37. Click Add
  38. Change the document as follows:
    @{
        ViewBag.Title = "Employees";
    }
    
    <h2>Gas Utility Company - Employees Portal</h2>
    
    <p>@Html.ActionLink("Create Employee Account", "AccountCreation")</p>
  39. In the Solution Explorer, expand Views and expand Shared
  40. Double-click _Layout.cshtml to open it
  41. Change the document as follows:
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gas Utility Company :: @ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    <link rel="stylesheet" type="text/css" href="~/Content/Utilities.css" />
    </head>
    <body>
    <header id="top-banner">
        <p class="text-center"><img src="~/Images/guc.png" alt="Gas Utility Company" width="649" height="74" /></p>
    </header>
    
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="centralizer">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                </div>
                <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">
                        <li>@Html.ActionLink("GUC Home", "Index", "Home")</li>
                        <li>@Html.ActionLink("Customers", "Index", "Customers")</li>
                        <li>@Html.ActionLink("Community", "Index", "Home")</li>
                        <li>@Html.ActionLink("Careers", "Index", "Home")</li>
                        <li>@Html.ActionLink("About GUC", "About", "Home")</li>
                        <li>@Html.ActionLink("Contact Us", "Contact", "Home")</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
    
    <div class="body-holder">
        <div class="col-md-3">
            <div class="topic">@Html.ActionLink("Safety", "Index", "Home")</div>
            <div class="topic">@Html.ActionLink("Outages", "Index", "Home")</div>
            <div class="topic">@Html.ActionLink("Commercial", "Index", "Home")</div>
            <div class="topic">@Html.ActionLink("Residential", "Index", "Home")</div>
            <div class="topic">@Html.ActionLink("Environment", "Index", "Home")</div>
            <div class="topic">@Html.ActionLink("Services/Appliances", "Index", "Customers")</div>
            <div class="topic">@Html.ActionLink("Community Relations", "Index", "Home")</div>
        </div>
        <div class="col-md-9">
            @RenderBody()
        </div>
    </div>
    
    <hr />
    
    <footer id="bottom-banner">
        <p id="copyright">&copy; @DateTime.Now.Year - Gas Utility Company</p>
    </footer>
    
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/bootstrap")
        @RenderSection("scripts", required: false)
    </body>
    </html>
  42. In the Solution Explorer, under Views, expand Home and double-click Index.cshtml to open it
  43. Change the document as follows:
    @{
        ViewBag.Title = "GUC Home";
    }
    
    <div class="jumbotron">
        <h1>Your Gas Needs With Us</h1>
        <p class="lead">The Gas Utility Company (GUC) serves the whole Metropolitan
            area and its vicinity. The company serves both residential and business
            needs in terms of natural gas.</p>
    </div>
    
    <div class="row">
        <div class="col-md-4">
            <h2>Employees</h2>
            <p>If you are an employee, make sure you log in in order to sign your
                time sheet and review available internal employment.</p>
            @Html.ActionLink("Employees Portal", "Index", "Employees")
        </div>
        <div class="col-md-4">
            <h2>Customers</h2>
            <p>In order to review or pay your bill, you must first log in. If you
                are not yet a customer, please create an account today.</p>
            @Html.ActionLink("Customers Topics", "Index", "Customers")
        </div>
        <div class="col-md-4">
            <h2>Community</h2>
            <p>This section provides much information about GUC's interactions
                with its community and its environment.</p>
            @Html.ActionLink("Community Relations", "Index", "Home")
        </div>
    </div>
  44. To execute the project, on the main menu, click Debug -> Start Without Debugging:

    Introduction to Characters and Strings

  45. Click the Employees Portal link
  46. On the Employees webpage, click the Create Employee Account link:

    Introduction to Characters and Strings

  47. Click the Customers button
  48. On the Customers webpage, click the Customer Invoice Preparation link:

    Introduction to Characters and Strings

  49. Close the browser and return to your programming environment

Characters and Methods

Passing a Character to a Method

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

public class Employee
{
    public string EmploymentStatus;

    public 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:

@{ 
    Employee staff = new Employee();

    staff.GetEmploymentStatus('f');
}

<p>Employment Status: @staff.EmploymentStatus</p>

Returning a Character From a 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:

public class Employee
{
    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".

Introduction to Strings

Fundamentals of Strings

As we have seen so far, a string is one or a group of characters. Based on this, to get a string, you can create a group of characters and include them in double-quotes.

To support strings, the .NET Framework provides a class named String. This class is defined in 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.

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

Practical LearningPractical Learning: Creating Empty Strings

  1. In the Solution Explorer, under Views and under Employees, double-click AccountCreation.cshtml to access it
  2. Add code as follows:
    @{
        ViewBag.Title = "Employee  Account Creation";
    }
    
    <h2>Employee Account Creation</h2>
    
    <div class="horizontal-line"></div>
    
    @{
        int length = 0;
        int digits = 0;
        int symbols = 0;
        int lowercase = 0;
        int uppercase = 0;
        string strUsername = string.Empty;
        string strLastName = string.Empty;
        string strFirstName = string.Empty;
        string strMiddleName = string.Empty;
        string strNewPassword = string.Empty;
        string strErrorMessage = string.Empty;
        string strConfirmPassword = string.Empty;
    
        if (IsPost)
        {
    
        }
    }
    
    @using (Html.BeginForm())
    {
        <table>
            <tr>
                <td class="left-col">First Name:</td>
                <td>@Html.TextBox("txtFirstName", @strFirstName)</td>
            </tr>
            <tr>
                <td>Middle Name:</td>
                <td>@Html.TextBox("txtMiddleName", @strMiddleName)</td>
            </tr>
            <tr>
                <td>Last Name:</td>
                <td>@Html.TextBox("txtLastName", @strLastName)</td>
            </tr>
            <tr>
                <td>Username:</td>
                <td>@strUsername</td>
            </tr>
        </table>
        <div class="horizontal-line"></div>
        <table>
            <tr>
                <td class="left-col">New Password:</td>
                <td>@Html.TextBox("txtNewPassword", @strNewPassword)</td>
                <td>@Html.TextBox("txtCharacters", @length, new { @class = "small-text" }) Characters</td>
            </tr>
            <tr>
                <td>Confirm Password:</td>
                <td>@Html.TextBox("txtConfirmPassword", @strConfirmPassword)</td>
                <td>&nbsp;</td>
            </tr>
        </table>
        <table>
            <tr>
                <td class="left-col">&nbsp;</td>
                <td class="large">@Html.TextBox("txtLowercase", @lowercase, new { @class = "small-text" }) Lowercase Letters</td>
                <td>@Html.TextBox("txtUppercase", @uppercase, new { @class = "small-text" }) Uppercase Letters</td>
            </tr>
            <tr>
                <td class="left-col">&nbsp;</td>
                <td>@Html.TextBox("txtDigits", @digits, new { @class = "small-text" }) Digits</td>
                <td>@Html.TextBox("txtSymbols", @symbols, new { @class = "small-text" }) Symbols</td>
            </tr>
        </table>
        <div class="horizontal-line"></div>
        <p class="text-center"><input type="submit" name="btnSubmit" value="Submit" class="btnLarge" /></p>
        <div class="horizontal-line"></div>
    
        <p>@strErrorMessage</p>
    }
  3. To execute the project, on the main menu, click Debug -`Start Without Debugging:
  4. Close the browser and return to your programming environment

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.

Practical LearningPractical Learning: Converting an Object to a String

The Length of a String

The length of a string, also referred to as its size, is the number of symbols or charaters 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:

<!DOCTYPE html>
<html>
<head>
<title>Numbers</title>
</head>
<body>

@{
    string gender = "Female";
}

@{
    <p>@gender contains @gender.Length characters</p>
}
</body>
</html>

This would produce:

The Length of a String

Practical LearningPractical Learning: Introducing the Number of Characters

  1. Change the code as follows:
    . . . No Change
    
    @{ 
        int length = 0;
        int digits = 0;
        int symbols = 0;
        int lowercase = 0;
        int uppercase = 0;
        string strNewPassword = string.Empty;
        string strErrorMessage = string.Empty;
        string strConfirmPassword = string.Empty;
    
        if (IsPost)
        {
            strNewPassword = Request["txtNewPassword"].ToString();
            length = strNewPassword.Length;
            strConfirmPassword = Request["txtConfirmPassword"].ToString();
        }
    }
    
    . . . No Change
    
  2. To execute the project, on the main menu, click Debug -`Start Without Debugging:

    Introduction to Characters and Strings

  3. In the New Password text box, type something, such as password

    The Length of a String

  4. Click the Submit button:

    The Length of a String

  5. Close the browser and return to your programming environment

The Characters of a String

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.

A String as an Array of Characters

To support strings, the .NET Framework provides the String class. This class is defined in the C# language as the string data type. Here is an example of declaring, initializing, and using a string object:

@{
    string gender = "Female";
}

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:

<!DOCTYPE html>
<html>
<head>
<title>Person</title>
</head>
<body>
@{
    string gender = "Female";
}

<p>Gender: @gender</p>
<p>Individual Characters</p>
@foreach(char c in gender)
{
    <p>Character: @c</p>
}
</body>
</html>

This would produce:

Character Presention

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:

<!DOCTYPE html>
<html>
<head>
<title>Person</title>
</head>
<body>
<table border="1">
    <tr>
        <td style="width: 180px; font-weight: bold"><b>Proposition</b></td><td><b>Conclusion</b></td>
    </tr>
    <tr>
        <td>q is a Letter</td><td>@Char.IsLetter('q')</td>
    </tr>
    <tr>
        <td>a is a lowercase letter</td><td>@Char.IsLower('a')</td>
    </tr>
    <tr>
        <td>W is an uppercase letter</td><td>@Char.IsUpper('W')</td>
    </tr>
    <tr>
        <td>1 is a digit</td><td>@Char.IsDigit('1')</td>
    </tr>
    <tr>
        <td>w is a letter or a digit</td><td>@Char.IsLetterOrDigit('w')</td>
    </tr>
    <tr>
        <td>3 is a letter or a digit</td><td>@Char.IsLetterOrDigit('w')</td>
    </tr>
    <tr>
        <td>0 is a number</td><td>@Char.IsNumber('0')</td>
    </tr>
    <tr>
        <td>_ is a punctuation mark</td><td>@Char.IsPunctuation('_')</td>
    </tr>
    <tr>
        <td># is a punctuation mark</td><td>@Char.IsPunctuation('#')</td>
    </tr>
    <tr>
        <td>\\ is a punctuation mark</td><td>@Char.IsPunctuation('\\')</td>
    </tr>
    <tr>
        <td> is a white space</td><td>@Char.IsWhiteSpace(' ')</td>
    </tr>
    <tr>
        <td> is a separator</td><td>@Char.IsSeparator(' ')</td>
    </tr>
    <tr>
        <td>+ is a symbol</td><td>@Char.IsSymbol('+')</td>
    </tr>
</table>
</body>
</html>

This would produce:

Character Presention

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

Practical LearningPractical Learning: Checking the Types of Characters

  1. Change the code of the AccountCreation.cshtml file as follows:
    @{
        ViewBag.Title = "Employee Account Creation";
    }
    
    <h2>Employee Account Creation</h2>
    
    <div class="horizontal-line"></div>
    
    @{ 
        int length = 0;
        int digits = 0;
        int symbols = 0;
        int lowercase = 0;
        int uppercase = 0;
    string strUsername = string.Empty;
    string strLastName = string.Empty;
    string strFirstName = string.Empty;
    string strMiddleName = string.Empty;
    string strNewPassword = string.Empty;
    string strErrorMessage = string.Empty;
    string strConfirmPassword = string.Empty; if (IsPost) { strNewPassword = Request["txtNewPassword"].ToString(); length = strNewPassword.Length; strConfirmPassword = Request["txtConfirmPassword"].ToString(); for (int i = 0; i < length; i++) { if (Char.IsDigit(strNewPassword[i])) { digits++; } if (Char.IsSymbol(strNewPassword[i]) || Char.IsPunctuation(strNewPassword[i])) { symbols++; } if (Char.IsLower(strNewPassword[i])) { lowercase++; } if (Char.IsUpper(strNewPassword[i])) { uppercase++; } } } } @using (Html.BeginForm()) { . . . No Change }
  2. To execute the project, on the main menu, click Debug -> Start Without Debugging:

    Introduction to Characters and Strings

  3. In the New Password text box, type something, such as $0uthD@koTA1889. Here is an example:

    The Length of a String

  4. Click the Submit button:

    The Length of a String

  5. Close the browser and return to your programming environment

Previous Copyright © 2001-2019, FunctionX Next