Home

Visual Basic Strings

Fundamentals of Strings

Introduction to Strings

A string is one or a combination of characters. To support strings, the Visual Basic language provides the String data types. The .NET Framework provides a class named String that is defined in the System namespace. That class provides tremendous additional support for strings using properties and methods.

Creating a String

To declare a variable for a string, you can use either the String data type of the Visual Basic language or the Object class of the .NET Framework. To initialize a string variable, put its value in double-quotes and assign it to the variable. Here is an example:

<%
Dim FirstName As Object

FirstName = "William"
%>

If the string is long, you can include it on many lines. Here are examples:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<script runat="server">
Sub ddlSelectionSelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
    Select Case ddlSelection.SelectedItem.Text
        Case "Introduction"
            txtDescription.Text = "Social sciences cover a wide range of studies that address 
all types of topics about human beings, their behaviors, their history, their societies, and their 
environments. Some social science topics are grouped in categories, such as individual or crowd, 
where studies tend to address the same categorical isssues."
        Case "Linguistics"
            txtDescription.Text = "Linguistics is the study of one or a family of languages. 
Linguistics studies the science, the technology, the mechanical, and physical aspects that rule 
a language. Linguistics scientifically describes the sound produced when a particular language 
is spoken, how, and usually why a certain sound is produced. Linguistics does not present or 
boast the beauties of a language, but linguistics can present some lacking features or 
describes some strengths. These aspects would lead to bias, deceiving the purpose of this science."
        Case "Philosophy"
            txtDescription.Text = "Philosophy is the study of existense (or being), 
knowledge (or reasoning), and truth. Philosophy seeks to comprehend what 
truth is, how to evaluate it, and how it influences thoughts and ethics. 
Like other social science topics such as sociology or psychology, philosophy 
examines both personal and crowd behavior but only as they relate to the 
mind. An example is the thinking process that results in someone taking one 
action rather than another (another person taking the same action or another 
person taking a different action). Unlike the other social science fields, 
philosophy doesn't concentrate on what is good or bad, or what is practical 
or weird, or on how something should (is supposed to) be. Instead, 
philosophy delves into the logic and the ethical reasons of what it (such 
as something or a behavior) is."
        Case "Psychology"
            txtDescription.Text = "Psychology is a social science field that focuses on 
the mind as it relates to human thoughts and behaviors. On one hand, 
psychology gets inputs from sociology, philosophy, medicine, and ethnicity, 
etc. on the other hand, psychology has a great influence on all sciences 
that deal with personal views and actions.

Psychology does Not exclusively targets the 
individual but it also considers any aspect in the   person's environment. 
As a matter of facts, there are various fields of studies that derive from 
psychology."
    End Select
End Sub
</script>
<html>
<head runat="server">
    <title>Social Science Studies</title>
</head>
<body>
    <h3>Social Science Studies</h3>

    <form id="frmSocialScience" runat="server">
    <div>
    <table>
        <tr>
            <td>Area of Study:</td>
            <td><asp:DropDownList id="ddlSelection"
                AutoPostBack="true"
                OnSelectedIndexChanged="ddlSelectionSelectedIndexChanged"
                 runat="server">
              <asp:ListItem>Introduction</asp:ListItem>
                <asp:ListItem>Linguistics</asp:ListItem>
              <asp:ListItem>Philosophy</asp:ListItem>
              <asp:ListItem>Psychology</asp:ListItem>
            </asp:DropDownList></td>
        </tr>
        <tr>
            <td style="vertical-align: top">Description:</td>
            <td><asp:TextBox id="txtDescription" TextMode="MultiLine"
                Columns="40" Rows="5" runat="server">
            </asp:TextBox></td>
        </tr>
    </table>
    </div>
    </form>
</body>
</html>

To include a double-quote in a string, double the double-quote. Here are examples:

<%@ Page Language="VB" %>

<!DOCTYPE html>
<html>
<head>
<title>Exercise</title>
</head>
<body>
<div align="center">
<%
Dim name = "Stanley"
Dim full = "Stan Ley"

Response.Write("It would be interesting to compare """ & name & """ with """ & full & """quot;)
%>
</body>
</html>

This would produce:

To include a double-quote in a string, double the double-quote.

String Concatenation

String concatenation consists of adding one string to another. To support this operation, the Visual Basic language provides the & operator. Here is an example of using it:

<%@ Page Language="VB" %>

<!DOCTYPE html>
<html>
<head>
<script runat="server">
Public Class Employee
    Public EmployeeNumber As String
    Public FirstName As String
    Public MiddleName As String
    Public MI As Char
    Public LastName As String
    Public Username As String
    Public Password As String
    Public SocialSecurityNumber As String
    Public PhoneNumber As String

    Public Sub New(ByVal emplNumber As String,
                   ByVal fName As String, ByVal lName As String)
        EmployeeNumber = emplNumber
        FirstName = fName
        LastName = lName
    End Sub
End Class

Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    Dim rndEmployeeNumber As New Random
    
    txtEmployeeNumber.Text = rndEmployeeNumber.Next(10000, 99999)

    txtUsername.Text = txtFirstName.Text & txtMiddleName.Text & txtLastName.Text
End Sub

Sub btnCreateRecordClick(ByVal sender As Object, ByVal e As EventArgs)
    Dim staff As Employee

    staff = New Employee(txtEmployeeNumber.Text,
			 txtFirstName.Text, txtLastName.Text)
    staff.MiddleName = txtMiddleName.Text
    staff.Username = txtUsername.Text
    staff.Password = txtPassword.Text
    staff.SocialSecurityNumber = txtSocialSecurityNumber.Text
    staff.PhoneNumber = txtPhoneNumber.Text

    lblEmployeeNumber.Text = txtEmployeeNumber.Text
    lblEmployeeName.Text = staff.LastName
    lblUsername.Text = staff.Username
    lblPassword.Text = staff.Password
    lblSocialSecurityNumber.Text = staff.SocialSecurityNumber
    lblPhoneNumber.Text = staff.PhoneNumber

    pnlRecord.Visible = True
    pnlApplication.Visible = False
End Sub
</script>
<title>Department Store - Employment Application</title>
</head>
<body>
<div align="center">
<h3>Department Store - Employment Application</h3>

<form id="frmEmploymentApplication" runat="server">
<asp:Panel id="pnlApplication" Visible="True" runat="server">
<table>
  <tr>
    <td>Employee #:</td>
    <td><asp:TextBox id="txtEmployeeNumber" runat="server" /></td>
  </tr>
  <tr>
    <td>First Name:</td>
    <td><asp:TextBox id="txtFirstName" AutoPostBack="True" runat="server" /></td>
  </tr>
  <tr>
    <td>Middle Name:</td>
    <td><asp:TextBox id="txtMiddleName" AutoPostBack="True" runat="server" /></td>
  </tr>
  <tr>
    <td>Last Name:</td>
    <td><asp:TextBox id="txtLastName" AutoPostBack="True" runat="server" /></td>
  </tr>
    <tr>
    <td>Social Security #:</td>
    <td><asp:TextBox id="txtSocialSecurityNumber" runat="server" /></td>
  </tr>
  <tr>
    <td>Phone Number:</td>
    <td><asp:TextBox id="txtPhoneNumber" runat="server" /></td>
  </tr>
    <tr>
    <td>Username:</td>
    <td><asp:TextBox id="txtUsername" runat="server" /></td>
  </tr>
  <tr>
    <td>Password:</td>
    <td><asp:TextBox id="txtPassword" AutoPostBack="True"
    		     Text="Password1" runat="server" /></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td><asp:Button id="btnCreateEmployeeRecord"
                    text="Create Employee Record"
                    OnClick="btnCreateRecordClick"
                    runat="server"></asp:Button> </td>
  </tr>
</table>
</asp:Panel>

<asp:Panel id="pnlRecord" Visible="False" runat="server">
<table>
  <tr>
    <td>Employee #:</td>
    <td><asp:Label id="lblEmployeeNumber" runat="server" /></td>
  </tr>
  <tr>
    <td>Employee Name:</td>
    <td><asp:Label id="lblEmployeeName" runat="server" /></td>
  </tr>
  <tr>
    <td>Social Security #:</td>
    <td><asp:Label id="lblSocialSecurityNumber" runat="server" /></td>
  </tr>
  <tr>
    <td>Phone Number:</td>
    <td><asp:Label id="lblPhoneNumber" runat="server" /></td>
  </tr>
  <tr>
    <td>Username:</td>
    <td><asp:Label id="lblUsername" runat="server" /></td>
  </tr>
  <tr>
    <td>Password:</td>
    <td><asp:Label id="lblPassword" runat="server" /></td>
  </tr>
</table>
</asp:Panel>
</form>
</div>
</body>

<asp:Panel id="pnlMessageHolder" Visible="True" runat="server">
  <asp:Label id="lblMessage" runat="server"></asp:Label>
</asp:Panel>
</html>

Here is an example of using the webpage:

A Null, Empty, or White-Spaced String

String Concatenation

String Concatenation

String Concatenation

Besides the & operator, to formally support string concatenation, the String class is equipped with a method named Concat. One of the versions of this method takes two String arguments. Its syntax is:

Public Shared Function Concat(str0 As String,
			      str1 As String) As String

This version takes two strings that should be concatenated. The method returns a new string as the first added to the second. If you need to concatenate three strings, another version of this method uses the following syntax:

Public Shared Function Concat(str0 As String,
			      str1 As String,
			      str2 As String) As String

Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<title>Exercise</title>
</head>
<body>
<%
Dim FirstName As String
Dim LastName As String
Dim FullName As String

FirstName = "William"
LastName = "Sansen"
FullName  = String.Concat(FirstName, " ", LastName)

Response.Write("Employee Name: " & FullName)
%>
</body>
</html>

This would produce:

String Concatenation

If you need to concatenate four strings, another version of this method uses the following syntax::

Public Shared Function Concat(str0 As String,
			      str1 As String,
			      str2 As String,
			      str3 As String) As String

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:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<title>Strings</title>
</head>
<body>
<%
Dim FullName As String

FullName = "Sansen"
FullName &= ", "
FullName &= "William"

Response.Write("Employee Name: " & FullName)
%>
</body>
</html>

This would produce:

Compound Concatenation

Formatting a String or a Value

Formatting a String in .NET

Formatting a string consists of inserting some characteris in it to control how it should be presented as an object. To support this operation, the String class is equipped with a shared method named Format. The String.Format() method is overloaded in various versions. One of its versions uses the following syntax:

Public Shared Function Format(format As String,
			      arg0 As Object) As String

The first argument can contain a string and a format as {0}. This is called a placeholder for a string or a number. The second argument is the value that would be used in place of the {0} placeholder of the first argument. If you need two placeholders for values, use the following version of the method:

Public Shared Function Format(format As String,
			      arg0 As Object,
			      arg1 As Object) As String

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 Shared Function Format(format As String,
			      arg0 As Object,
			      arg1 As Object,
			      arg2 As Object) As String

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}. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<script runat="server">
Public Class SalaryEstimation
        Private hSalary As Double

        Public Sub New(ByVal salary)
            hSalary = salary
        End Sub

        Public ReadOnly Property HourlySalary() As Double
            Get
                If hSalary < 0.0 Then
                    Return 0.0
                Else
                    Return hSalary
                End If
            End Get
        End Property

        Public ReadOnly Property WeeklySalary() As Double
            Get
                Return HourlySalary * 40
            End Get
        End Property

        Public ReadOnly Property BiWeeklySalary() As Double
            Get
                Return WeeklySalary * 2.0
            End Get
        End Property

        Public ReadOnly Property MonthlySalary() As Double
            Get
                Return WeeklySalary * 4.0
            End Get
        End Property

        Public ReadOnly Property YearlySalary() As Double
            Get
                Return MonthlySalary * 12.0
            End Get
        End Property
End Class

Sub btnEvaluateClick() Handles btnEvaluate.Click
        Dim hr As Double
        Dim results As String
        Dim estimate As SalaryEstimation

        hr = CDbl(txtHourlySalary.Text)
        estimate = New SalaryEstimation(hr)

        results = String.Format("{0}/week, or {1}/month, or {2}/year",
                                estimate.HourlySalary , estimate.WeeklySalary,
                                estimate.MonthlySalary, estimate.YearlySalary)
        lblResults.Text = results

        lblSalary.Visible = True
        lblResults.Visible = True
End Sub
</script>
<style>
#estimation {  width: 420px }
</style>
<title>Salary Estimation</title>
</head>
<body>
<form id="frmEstimation" runat="server">

<h2>Salary Estimation</h2>

<table id="estimation">
  <tr>
    <td><b>Hourly Salary:</b></td>
    <td><asp:TextBox id="txtHourlySalary" Width="75px" runat="server"></asp:TextBox>
        <asp:Button id="btnEvaluate" Text="Evaluate" runat="server" />
    </td>
  </tr>
  <tr>
    <td><b><asp:Label id="lblSalary" Text="Salary Evaluation"
    		      Visible="False" runat="server" /></b></td>
    <td><asp:Label id="lblResults" Visible="False" runat="server"></asp:Label></td>
  </tr>
</table>

</form>
</body>
</html>

Here is an example of using the webpage:

Formatting a String

Formatting a String

Formatting a String

By the way, you can call other functions for the value(s) of the argument(s) after the first argument. Here is an example:

<script runat="server">
Sub btnEvaluateClick() Handles btnEvaluate.Click
    Dim hr As Double
    Dim results As String
    Dim estimate As SalaryEstimation

    hr = CDbl(txtHourlySalary.Text)
    estimate = New SalaryEstimation(hr)

    results = String.Format("{0}/week, or {1}/month, or {2}/year",
                            estimate.HourlySalary,
                            Format(estimate.WeeklySalary, "n"),
                            Format(estimate.MonthlySalary, "standard"),
                            Format(estimate.YearlySalary, "STANDARD"))
    lblResults.Text = results
End Sub
</script>

Here is an example of using the webpage:

Formatting a String

Formatting a String

Formatting a String

If you need more than three placeholders for values, use the following version of the method:

Public Shared Function Format(format As String,
			      ParamArray args As Object()) As String

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.

Numeric Formatting

Introduction

Number formatting consists of specifying how a number should display on a form or a webpage. To support it, the Visual Basic language provides a function named Format. This function can be used for different types of values The most basic technique consists of passing it an expression that holds the value to display. The syntax of this function is:

Public Shared Function Format(ByVal Expression As Object,
			      Optional ByVal Style As String = "") As String

The simplest way to use this function is to pass it a number or a string as argument. The function would then produce that number. Besides the Format() function, the Visual Basic language provides some additional functions we will review below.

To control how the number should display, you can pass the second argument of the Format() function. This argument would be passed as a string.

A Number in a General Format

A number is in general format if it doesn't use the character known as the thousand separator, which, in US English, is the comma. To display a number in a general format, pass "G" or "g" as the second argument of the Format() function. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head>
<script runat="server">
Sub Identify(ByVal Number As Long, ByVal FirstName As String,
             ByVal LastName As String, ByVal MiddleInitial As Char)
    Response.Write(CStr(Number) & ": " & FirstName & " " &
                        MiddleInitial & ". " & LastName )
End Sub

Function CalculateNetPay(ByVal HourlyRate As Double,
                         ByVal TotalTime As Double) As Double
    Return HourlyRate * TotalTime
End Function
</script>

<title>Employee Payroll</title>
</head>
<body>
<h3>Employee Payroll</h3>

<%
Dim HourlySalary = 24.2
Dim TimeWorked = 42.5
Dim Pay = CalculateNetPay(TotalTime := TimeWorked, HourlyRate := HourlySalary)

Response.Write("<b>Employee:</b> ")
Identify(FirstName := "Justine", LastName := "Gibbs",
         Number := 381751, MiddleInitial :=  "V"c)
Response.Write("<br><b>Hourly Salary:</b> " & Format(HourlySalary, "g"))
Response.Write("<br><b>Time Worked:</b> " & Format(TimeWorked, "G"))
Response.Write("<br><b>Net Pay:</b> " & Format(Pay, "G"))
%>

</body>
</html>

This would produce:

A Number in a General Format

A Number in a Fixed Format

To display a number in a fixed format, pass the second argument as "F" or "f". A number is in a fixed format if:

  • It uses the character considered as the decimal separator, which, in US English, is the period
  • On the left side of the decimal separator, there will be at least one digit. For example, if you provide a number such as .5, the function would use 0 on the left of the period
  • The number will display with 2 digits on the right side of the decimal separator. If the argument is provided as a natural number, the function would add .00 to the right side of the number. Here is an example:
    <%@ Page Language="VB" %>
    
    <!DOCTYPE html>
    <html>
    <head>
    <script runat="server">
    Sub btnCalculateClick(ByVal sender As Object, ByVal e As EventArgs)
        Dim pricePerCCF As Double
        Dim monthlyCharges As Double
        Dim consumption As Double
    
        pricePerCCF = 50.0
        monthlyCharges = 0.0
        consumption = CDbl(txtConsumption.Text)
    
        If consumption >= 0.50 Then
            pricePerCCF = 35.00
        End If
    
        txtPricePerCCF.Text = pricePerCCF
    
        pricePerCCF = CDbl(txtPricePerCCF.Text)
    
        monthlyCharges = consumption * pricePerCCF
    
        txtMonthlyCharges.Text = Format(monthlyCharges, "F")
    End Sub
    </script>
    <title>Gas Utility Company</title>
    </head>
    <body>
    <div align="center">
    
    <form id="frmBillPreparation" runat="server">
    <h3>Gas Utility Company</h3>
    
    <table border=0>
      <tr>
        <td>Consumption:</td>
        <td><asp:TextBox id="txtConsumption"
                         text="0.00" runat="server" /></td>
      </tr>
      <tr>
        <td>&nbsp</td>
        <td style="text-align: center">
            <asp:Button id="btnCalculate"
                        text="Calculate"
                        OnClick="btnCalculateClick"
                        runat="server"></asp:Button></td>
      </tr>
      <tr>
        <td>Price Per CCF:</td>
        <td><asp:TextBox id="txtPricePerCCF" text="0.00" runat="server" /></td>
      </tr>
        <tr>
        <td>Monthly Charges:</td>
        <td><asp:TextBox id="txtMonthlyCharges" text="0.00" runat="server" /></td>
      </tr>
    </table>
    </form>
    </div>
    </body>
    </html>
    Here is an example of using the webpage:

    Creating a Boolean Condition

    A Number in a Fixed Format

    If the value is provided with one digit on the right side the decimal separator, the function would add 0 as the last digit. If the value is passed with more than one digit, the function would reduce it to two digits using the same mechanism as the Floor() or the Ceiling() function.Here is an example:

A Number in a Standard Format

The standard format is a combination of the general and the fixed formats: The number must use the decimal separator and the thousands separator, including the mechanisms to reconcile the digits on both sides of the decimal separator. To display a number in the standard format, you have various options. You can pass the second argument of the Format() function as "n" or as "N". Here are examples:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<script runat="server">
Sub btnCalculateClick(ByVal sender As Object, ByVal e As EventArgs)
        Dim periods = 0.00
        Dim principal = 0.00
        Dim futureValue = 0.00
        Dim interestRate = 0.00
        Dim interestEarned = 0.00
        Dim compoundFrequency = 0.00

        principal = txtPrincipal.Text
        interestRate = txtInterestRate.Text / 100.0
        periods = txtPeriods.Text

        If ddlCompounded.Text = "Daily" Then
            compoundFrequency = 365
        ElseIf ddlCompounded.Text = "Weekly" Then
            compoundFrequency = 52.0
        ElseIf ddlCompounded.Text = "Monthly" Then
            compoundFrequency = 12.0
        ElseIf ddlCompounded.Text = "Quarterly" Then
            compoundFrequency = 4.0
        ElseIf ddlCompounded.Text = "Semiannually" Then
            compoundFrequency = 2.0
        Else ' if compounding = Annually then
            compoundFrequency = 1.0
        End If

        futureValue = principal * Math.Pow((1.0 + (interestRate / compoundFrequency)), compoundFrequency * periods)
        interestEarned = futureValue - principal

        txtInterestEarned.Text = Format(interestEarned, "N")
        txtFutureValue.Text = Format(futureValue, "n")
End Sub
</script>
<style>
#container
{
    margin: auto;
    width:  355px;
}
#math {  width: 350px; }
</style>
<title>Compound Interest</title>
</head>
<body>
<form id="frmBusiness" runat="server">
<div id="container">

<h3>Compound Interest</h3>

<table>
  <tr>
    <td><b>Principal:</b></td>
    <td><asp:TextBox id="txtPrincipal" Width="75px" runat="server"></asp:TextBox></td>
  </tr>
  <tr>
    <td><b>Interest Rate:</b></td>
    <td><asp:TextBox id="txtInterestRate" Width="55px" runat="server"></asp:TextBox>%</td>
  </tr>
  <tr>
    <td><b>Periods:</b></td>
    <td><asp:TextBox id="txtPeriods" Width="55px" runat="server"></asp:TextBox>Years</td>
  </tr>
  <tr>
    <td><b>Compounded:</b>
    </td>
    <td>
      <asp:DropDownList id="ddlCompounded" Width="120px" runat="server">
        <asp:ListItem>Daily</asp:ListItem>
        <asp:ListItem>Weekly</asp:ListItem>
        <asp:ListItem>Monthly</asp:ListItem>
        <asp:ListItem>Quarterly</asp:ListItem>
        <asp:ListItem>Semiannually</asp:ListItem>
        <asp:ListItem>Annually</asp:ListItem>
      </asp:DropDownList>
        <asp:Button id="btnCalculate" Text="Calculate" OnClick="btnCalculateClick" runat="server" />
    </td>
  </tr>
  <tr>
    <td><b>Interest Earned:</b></td>
    <td><asp:TextBox id="txtInterestEarned" runat="server"></asp:TextBox></td>
  </tr>
  <tr>
      <td><b>Future Value:</b></td>
    <td><asp:TextBox id="txtFutureValue" runat="server"></asp:TextBox></td>
  </tr>
</table>
</div>
</form>
</body>
</html>

Here is an example of using the webpage:

A Number in a Standard Format

A Number in a Standard Format

A Number in a Standard Format

You can also pass the second argument as "standard" (case-insensitive). Here are examples:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head run>
<style>
#container
{
    margin: auto;
    width:   225px;
}
#estimation {
    width:   230px;
}
</style>
<title>Salary Estimation</title>
</head>
<body>
<div id="container">

<%
Dim HourlySalary   = 24.2
Dim WeeklySalary   = HourlySalary * 40
Dim BiWeeklySalary = WeeklySalary  * 2
Dim MonthlySalary  = WeeklySalary * 4
Dim YearlySalary   = MonthlySalary * 12

Response.Write("<h2>Salary Estimation</h2>")
Response.Write("<table border=6 id='estimation'>")
Response.Write("<tr><td><b>Hourly Salary:</b></td><td>" & Format(HourlySalary, "N") & "</td></tr>")
Response.Write("<tr><td><b>Weekly Salary:</b></td><td>" & Format(WeeklySalary, "n") & "</td></tr>")
Response.Write("<tr><td><b>Bi-Weekly Salary:</b></td><td>" & Format(BiWeeklySalary, "n") & "</td></tr>")
Response.Write("<tr><td><b>Monthly Salary:</b></td><td>" & Format(MonthlySalary, "standard") & "</td></tr>")
Response.Write("<tr><td><b>Yearly Salary:</b></td><td>" & Format(YearlySalary, "STANDARD") & "</td></tr></table>")
%>

</div>
</body>
</html>

This would produce:

Numeric Formatting

As an alternative, the Visual Basic language provides a function named FormatNumber. Its syntax is:

Public Shared Function FormatNumber(
   ByVal Expression As Object,
   Optional ByVal NumDigitsAfterDecimal As Integer = -1,
   Optional ByVal IncludeLeadingDigit As TriState = TriState.UseDefault,
   Optional ByVal UseParensForNegativeNumbers As TriState = TriState.UseDefault,
   Optional ByVal GroupDigits As TriState = TriState.UseDefault) As String

Here are examples of calling the function:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<script runat="server">
Sub btnCalculateClick(ByVal sender As Object, ByVal e As EventArgs)
    Dim length As Double
    Dim area As Double
    Dim volume As Double

    length = CDbl(txtEdgeLength.Text)

    area = length * length * 2.0 * Math.Sqrt(3.0)
    volume = length * length * length * Math.Sqrt(2.0) / 3.0

    txtSurfaceArea.Text = FormatNumber(area)
    txtVolume.Text = FormatNumber(volume)
End Sub
</script>
<title>Geometry: Octahedron</title>
</head>
<body>
<div align="center">
<h2>Geometry: Octahedron</h2>

<form id="frmGeometry" runat="server">
<table>
  <tr>
    <td>Edge Length:</td>
    <td>
      <asp:TextBox runat="server"
	             id="txtEdgeLength" Text="1.00"></asp:TextBox>
	<asp:Button runat="server" id="btnCalculate"
                    Text="Calculate" OnClick="btnCalculateClick"></asp:Button></td>
    </tr>
    <tr>
      <td>Surface Area:</td>
      <td><asp:TextBox runat="server"
                       id="txtSurfaceArea" Text="0.00"></asp:TextBox></td>
    </tr>
    <tr>
      <td>Volume:</td>
      <td><asp:TextBox runat="server"
                       id="txtVolume" Text="0.00"></asp:TextBox></td>
    </tr>
  </table>
</form>
</div>
</body>
</html>

Here is an example of using the webpage:

Formatting a Number

Formatting a Number

Formatting a Number

Formatting a Monetary Value

To display a number as a monetary value, you can pass the second argument of the Format() function as "c" or "C". Here are examples:

<html>
<head runat="server">
<script runat="server">
Sub btnCalculateClick(ByVal sender As Object, ByVal e As EventArgs)
    Dim periods = 0
    Dim payment = 0.00
    Dim interestRate = 0.00
    Dim loanAmount = 0.00
    
    loanAmount = txtLoanAmount.Text
    interestRate = CDbl(txtInterestRate.Text) / 100.00
    periods = txtPeriods.Text

    payment = Pmt(interestRate / 12.00, periods, -loanAmount, 0.00, DueDate.EndOfPeriod)

    txtLoanAmount.Text = Format(loanAmount, "C")
    txtPayment.Text = Format(payment, "c")

End Sub
</script>
<style>
#container
{
    margin: auto;
    width:  345px;
}
</style>
<title>Business Mathematics - Musical Instrument Financing</title>
</head>
<body>
<form id="frmBusiness" runat="server">
<div id="container">

<h3>Business Mathematics</h3>
<h4>Musical Instrument Financing</h4>

<table>
  <tr>
    <td style="width: 140px"><b>Loan Amount:</b></td>
    <td><asp:TextBox id="txtLoanAmount" Width="75px" runat="server"></asp:TextBox></td>
  </tr>
  <tr>
    <td><b>Interest Rate:</b></td>
    <td><asp:TextBox id="txtInterestRate" Width="55px" runat="server"></asp:TextBox>%</td>
  </tr>
  <tr>
    <td><b>Number of Periods:</b></td>
    <td><asp:TextBox id="txtPeriods" Width="55px" runat="server"></asp:TextBox>Months
        <asp:Button id="btnCalculate" Text="Calculate"
        	    OnClick="btnCalculateClick" runat="server" /></td>
  </tr>
  <tr>
    <td style="width: 140px"><b>Loan Payment:</b></td>
    <td><asp:TextBox id="txtPayment" Width="75px" runat="server"></asp:TextBox>/Month</td>
  </tr>
</table>
</div>
</form>
</body>
</html>

Here is an example of using the webpage:

Formatting a Monetary Value

Formatting a Monetary Value

Formatting a Monetary Value

You can also pass the argument as "Currency" (case-insensitive). Here are examples:

<html>
<head runat="server">
<script runat="server">
Sub btnCalculateClick(ByVal sender As Object, ByVal e As EventArgs)
    Dim periods = 0
    Dim interestRate = 0.00
    Dim loanAmount = 0.00
    Dim regularPayment = 0.00
    Dim principalPayment = 0.00
    
    loanAmount = txtLoanAmount.Text
    interestRate = CDbl(txtInterestRate.Text) / 100.00
    periods = txtPeriods.Text

    loanAmount = Pmt(interestRate / 12.00, periods, -loanAmount, 0.00, DueDate.EndOfPeriod)
    principalPayment = PPmt(interestRate / 12.00, 1, periods, -loanAmount, 0.00, DueDate.EndOfPeriod)

    txtLoanAmount.Text = Format(loanAmount, "currency")
    txtLoanPayment.Text = Format(loanAmount, "CURRENCY")
    txtPrincipalPayment.Text = Format(principalPayment, "Currency")
End Sub
</script>
<style>
#container
{
    margin: auto;
    width:  345px;
}
</style>
<title>Business Mathematics - Boat Financing</title>
</head>
<body>
<form id="frmBusiness" runat="server">
<div id="container">

<h3>Business Mathematics - Boat Financing</h3>

<table>
  <tr>
    <td style="width: 140px"><b>Loan Amount:</b></td>
    <td><asp:TextBox id="txtLoanAmount" Width="75px" runat="server"></asp:TextBox></td>
  </tr>
  <tr>
    <td><b>Interest Rate:</b></td>
    <td><asp:TextBox id="txtInterestRate" Width="55px" runat="server"></asp:TextBox>%</td>
  </tr>
  <tr>
    <td><b>Number of Periods:</b></td>
    <td><asp:TextBox id="txtPeriods" Width="55px" runat="server"></asp:TextBox>Months
        <asp:Button id="btnCalculate" Text="Calculate" OnClick="btnCalculateClick" runat="server" /></td>
  </tr>
  <tr>
    <td style="width: 140px"><b>Loan Payment:</b></td>
    <td><asp:TextBox id="txtLoanPayment" Width="75px" runat="server"></asp:TextBox>/Month</td>
  </tr>
  <tr>
    <td style="width: 140px"><b>Principal Payment:</b></td>
    <td><asp:TextBox id="txtPrincipalPayment" Width="75px" runat="server"></asp:TextBox>/Month</td>
  </tr>
</table>
</div>
</form>
</body>
</html>

Here is an example of using the webpage:

The Payment Applied to the Principal

The Payment Applied to the Principal

The Payment Applied to the Principal

As an alternative, to let you control how a monetary value should be displayed, the Visual Basic language provides a function named FormatCurrency. Its syntax is:

Public Shared Function FormatCurrency(Expression As Object,
				      NumDigitsAfterDecimal As Integer,
				      IncludeLeadingDigit As TriState,
				      UseParensForNegativeNumbers As TriState,
				      GroupDigits As TriState) As String

Here are examples of calling this function:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<script runat="server">
Sub btnCalculateClick(ByVal sender As Object, ByVal e As EventArgs)
    Dim cost As Double
    Dim salvage As Double
    Dim life As Double
    Dim depreciation As Double

    cost = CDbl(txtPurchasePrice.Text)
    salvage = CDbl(txtSalvageValue.Text)
    life = CDbl(txtEstimatedLife.Text)

    depreciation = SLN(cost, salvage, life)

    txtPurchasePrice.Text = FormatCurrency(cost)
    txtSalvageValue.Text  = FormatCurrency(salvage)
    txtEstimatedLife.Text = FormatNumber(life, 0)
    txtDepreciation.Text  = FormatCurrency(depreciation)
End Sub
</script>
<title>Depreciation: Straight-Line Method</title>
</head>
<body>
<div align="center">
<h2>Depreciation: Straight-Line Method</h2>

<form id="frmDepreciation" runat="server">
<table>
  <tr>
    <td>Purchase Price:</td>
    <td>
      <asp:TextBox Runat="server"
	             id="txtPurchasePrice" Text="0.00"></asp:TextBox></td>
    </tr>
    <tr>
      <td>Salvage Value:</td>
      <td><asp:TextBox Runat="server"
                       id="txtSalvageValue" Text="0.00"></asp:TextBox></td>
    </tr>
    <tr>
      <td>Estimated Life:</td>
      <td><asp:TextBox Runat="server"
                  id="txtEstimatedLife" Text="0" Width="65px"></asp:TextBox> Year(s)
	<asp:Button Runat="server" id="btnCalculate"
                    Text="Calculate" OnClick="btnCalculateClick"></asp:Button></td>
    </tr>
    <tr>
      <td>Depreciation:</td>
      <td><asp:TextBox Runat="server" Width="65px"
                       id="txtDepreciation" Text="0.00"></asp:TextBox>/Year</td>
    </tr>
  </table>
</form>
</div>
</body>
</html>

Here is an example of using the webpage:

Formatting a Monetary Value

Formatting a Monetary Value

Formatting a Monetary Value

Formatting a Percentage Value

To let you specify how a percentage value should appear, the Visual Basic language provides the FormatPercent() function. Its syntax is:

Public Shared Function FormatPercent(Expression As Object,
				     NumDigitsAfterDecimal As Integer,
				     IncludeLeadingDigit As TriState,
				     UseParensForNegativeNumbers As TriState,
				     GroupDigits As TriState) As String

Other Techniques of Formatting a Number

To let you further control how a numhber should display, the second argument of the Format() function can include some special characters. To represent the integral part of a number, use the # symbol. You can enter as many # signs as you want. To specify the number of digits to display on the right side of the decimal separator, type a period on the right side of # followed by the number of 0s representing each decimal place. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<script runat="server">
Public Class Octagon
    Public Side As Double

    Public Sub New(ByVal side As Double)
        Me.Side = side
    End Sub

    Public Function CalculatePerimeter() As Double
        Return Me.Side * 8.00
    End Function

    Public Function CalculateArea() As Double
        Return Me.Side * Me.Side * 2.00 * (1.00 + Math.Sqrt(2.00))
    End Function
End Class

Sub btnCalculateClick(ByVal sender As Object, ByVal e As EventArgs)
        Dim plate As Octagon
        Dim side As Double

        side = CDbl(txtSide.Text)

        plate = New Octagon(side)

        txtPerimeter.Text = Format(plate.CalculatePerimeter(), "#.0000")
        txtArea.Text = Format(plate.CalculateArea(), "#.000000")
    End Sub
</script>
<style>
#container
{
    margin: auto;
    width:   305px;
}
#estimation {  width: 300px; }
</style>
<title>Geometry - Polygons: The Octagon</title>
</head>
<body>
<form id="frmGeometry" runat="server">
<div id="container">

<h3>Geometry - Polygons: The Octagon</h3>

<table id="estimation">
  <tr>
    <td><b>Side:</b></td>
    <td><asp:TextBox id="txtSide" Width="75px" runat="server"></asp:TextBox>
        <asp:Button id="btnCalculate" Text="Calculate"
        	    OnClick="btnCalculateClick" runat="server" />
    </td>
  </tr>
  <tr>
    <td><b>Perimeter:</b></td>
    <td><asp:TextBox id="txtPerimeter" runat="server"></asp:TextBox></td>
  </tr>
  <tr><td><b>Area:</b></td>
    <td><asp:TextBox id="txtArea" runat="server"></asp:TextBox></td>
  </tr>
</table>
</div>
</form>
</body>
</html>

Here is an example of using the webpage:

The Square Root of a Number

The Square Root of a Number

To specify that you want to display the decimal separator, include its character between the # signs.

Characters, Strings, and Procedures

Passing a Character or a String to a Procedure

Like a normal value, a character or a string can be passed to a procedure. When calling the procedure, you can pass a value for the argument in double-quotes.

Returning a Character or a String From a Function

You can create a function that returns a character or a string. This is done the same way as with the other classes.

Primary Characteristics of Strings

An Empty String

A string is referred to as empty if it contains no characters at all. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<title>Salary Estimation</title>
</head>
<body>
<%
Dim empty As String

empty = ""
%>
</body>
</html>

If you want to create a string made of one or more empty spaces, you can call the Space() function. Its syntax is:

Public Shared Function Space(ByVal Number As Integer) As String

Nothing as a String

A string is referred to as null or nothing if there is no way to define what it contains. To define such a string, declare a String variable and initialize it with Nothing. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<title>Salary Estimation</title>
</head>
<body>
<%
Dim whatever As String

whatever = Nothing

Response.Write("Whatever: " & whatever)
%>
</body>
</html>

As it is available to other objects, an alternative is to assign Nothing to a String variable.

A Null or Empty String

A string is referred to as null if it has lost its characters. For example, at one time a string may contain characters but those characters get deleted. If the string is/was stored in a variable, the variable may contain garbage.

To let you find out whether a string is empty or null, the String class is equipped with a shared method named IsNullOrEmpty. Its syntax is:

Public Shared Function IsNullOrEmpty(value As String) As Boolean

Here is an example of calling this method:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<script runat="server">
Public Class SalaryEstimation
        Private hSalary As Double

        Public Sub New(ByVal salary)
            hSalary = salary
        End Sub

        Public ReadOnly Property HourlySalary As Double
            Get
                If hSalary < 0.00 Then
                    Return 0.00
                Else
                    Return hSalary
                End If
            End Get
        End Property

        Public ReadOnly Property WeeklySalary As Double
            Get
                Return HourlySalary * 40
            End Get
        End Property

        Public ReadOnly Property BiWeeklySalary As Double
            Get
                Return WeeklySalary * 2.0
            End Get
        End Property

        Public ReadOnly Property MonthlySalary As Double
            Get
                Return WeeklySalary * 4.0
            End Get
        End Property

        Public ReadOnly Property YearlySalary As Double
            Get
                Return MonthlySalary * 12.0
            End Get
        End Property
End Class

Sub btnEvaluateClick() Handles btnEvaluate.Click
        Dim estimate As SalaryEstimation
        Dim hr As Double

        If String.IsNullOrEmpty(txtHourlySalary.Text) Then
            hr = 0.00
        Else
            hr = CDbl(txtHourlySalary.Text)
        End If

        estimate = New SalaryEstimation(hr)

        lblHourlySalary.Text = estimate.HourlySalary & "/hr"
        txtWeeklySalary.Text = Format(estimate.WeeklySalary, "n")
        txtBiWeeklySalary.Text = Format(estimate.BiWeeklySalary, "n")
        txtMonthlySalary.Text = Format(estimate.MonthlySalary, "standard")
        txtYearlySalary.Text = Format(estimate.YearlySalary, "STANDARD")
End Sub
</script>
<style>
#container
{
    margin: auto;
    width:   305px;
}
#estimation {  width: 300px; }
</style>
<title>Salary Estimation</title>
</head>
<body>
<form id="frmEstimation" runat="server">
<div id="container">

<h2>Salary Estimation</h2>

<table id="estimation">
  <tr>
    <td><b>Hourly Salary:</b></td>
    <td><asp:TextBox id="txtHourlySalary" Width="75px" runat="server"></asp:TextBox>
        <asp:Button id="btnEvaluate" Text="Evaluate" runat="server" />
    </td>
  </tr>
  <tr>
    <td><b>Based on:</b></td>
    <td><asp:Label id="lblHourlySalary" Width="75px"
                            runat="server"></asp:Label></td>
  </tr>
  <tr>
    <td><b>Weekly Salary:</b></td>
    <td><asp:TextBox id="txtWeeklySalary" Width="75px"
                     runat="server"></asp:TextBox></td>
  </tr>
  <tr><td><b>Bi-Weekly Salary:</b></td>
    <td><asp:TextBox id="txtBiWeeklySalary" Width="75px"
                     runat="server"></asp:TextBox></td></tr>
  <tr>
    <td><b>Monthly Salary:</b></td>
    <td><asp:TextBox id="txtMonthlySalary" Width="75px"
                     runat="server"></asp:TextBox></td>
  </tr>
  <tr><td><b>Yearly Salary:</b></td>
    <td><asp:TextBox id="txtYearlySalary" Width="75px"
                     runat="server"></asp:TextBox></td>
  </tr>
</table>
</div>
</form>
</body>
</html>

Here is an example of using the webpage:

A Null or Empty String

A Null or Empty String

A Null or Empty String

A Null, Empty, or White-Spaced String

To let you find out whether a string is empty, is null, or is made of white space characters, the String class is equipped with a shared method named IsNullOrWhiteSpace. Its syntax is:

Public Shared Function IsNullOrWhiteSpace(value As String) As Boolean

Here is an example of calling this method:

<%@ Page Language="VB" %>

<!DOCTYPE html>
<html>
<head>
<script runat="server">
Public Class Employee
        Public EmployeeNumber As String
        Public FirstName As String
        Public MiddleName As String
        Public MI As Char
        Public LastName As String
        Public Username As String
        Public Password As String
        Public SocialSecurityNumber As String
        Public PhoneNumber As String

        Public Sub New(ByVal emplNumber As String,
                       ByVal fName As String, ByVal lName As String)
            EmployeeNumber = emplNumber
            FirstName = fName
            LastName = lName
        End Sub
End Class

Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    Dim rndEmployeeNumber As New Random
    
    txtEmployeeNumber.Text = rndEmployeeNumber.Next(10000, 99999)
    
    If String.IsNullOrWhiteSpace(txtMiddleName.Text) Then
        txtUsername.Text = txtFirstName.Text & txtLastName.Text
    Else
        txtUsername.Text = txtFirstName.Text & txtMiddleName.Text & txtLastName.Text
    End If
End Sub

Sub btnCreateRecordClick(ByVal sender As Object, ByVal e As EventArgs)
        Dim staff As Employee

        staff = New Employee(txtEmployeeNumber.Text,
        		     txtFirstName.Text, txtLastName.Text)
        staff.MiddleName = txtMiddleName.Text
        staff.Username = txtUsername.Text
        staff.Password = txtPassword.Text
        staff.SocialSecurityNumber = txtSocialSecurityNumber.Text
        staff.PhoneNumber = txtPhoneNumber.Text

        lblEmployeeNumber.Text = txtEmployeeNumber.Text
        lblEmployeeName.Text = staff.LastName
        lblUsername.Text = staff.Username
        lblPassword.Text = staff.Password
        lblSocialSecurityNumber.Text = staff.SocialSecurityNumber
        lblPhoneNumber.Text = staff.PhoneNumber

        pnlRecord.Visible = True
        pnlApplication.Visible = False
End Sub
</script>
<title>Department Store - Employment Application</title>
</head>
<body>
<div align="center">
<h3>Department Store - Employment Application</h3>

<form id="frmEmploymentApplication" runat="server">
<asp:Panel id="pnlApplication" Visible="True" runat="server">
<table>
  <tr>
    <td>Employee #:</td>
    <td><asp:TextBox id="txtEmployeeNumber" runat="server" /></td>
  </tr>
  <tr>
    <td>First Name:</td>
    <td><asp:TextBox id="txtFirstName" AutoPostBack="True" runat="server" /></td>
  </tr>
  <tr>
    <td>Middle Name:</td>
    <td><asp:TextBox id="txtMiddleName" AutoPostBack="True" runat="server" /></td>
  </tr>
  <tr>
    <td>Last Name:</td>
    <td><asp:TextBox id="txtLastName" AutoPostBack="True" runat="server" /></td>
  </tr>
    <tr>
    <td>Social Security #:</td>
    <td><asp:TextBox id="txtSocialSecurityNumber" runat="server" /></td>
  </tr>
  <tr>
    <td>Phone Number:</td>
    <td><asp:TextBox id="txtPhoneNumber" runat="server" /></td>
  </tr>
    <tr>
    <td>Username:</td>
    <td><asp:TextBox id="txtUsername" runat="server" /></td>
  </tr>
  <tr>
    <td>Password:</td>
    <td><asp:TextBox id="txtPassword" AutoPostBack="True"
    		     Text="Password1" runat="server" /></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td><asp:Button id="btnCreateEmployeeRecord"
                    text="Create Employee Record"
                    OnClick="btnCreateRecordClick"
                    runat="server"></asp:Button> </td>
  </tr>
</table>
</asp:Panel>

<asp:Panel id="pnlRecord" Visible="False" runat="server">
<table>
  <tr>
    <td>Employee #:</td>
    <td><asp:Label id="lblEmployeeNumber" runat="server" /></td>
  </tr>
  <tr>
    <td>Employee Name:</td>
    <td><asp:Label id="lblEmployeeName" runat="server" /></td>
  </tr>
  <tr>
    <td>Social Security #:</td>
    <td><asp:Label id="lblSocialSecurityNumber" runat="server" /></td>
  &llt;/tr>
  <tr>
    <td>Phone Number:</td>
    <td><asp:Label id="lblPhoneNumber" runat="server" /></td>
  </tr>
  <tr>
    <td>Username:</td>
    <td><asp:Label id="lblUsername" runat="server" /></td>
  </tr>
  <tr>
    <td>Password:</td>
    <td><asp:Label id="lblPassword" runat="server" /></td>
  </tr>
</table>
</asp:Panel>
</form>
</div>
</body>

<asp:Panel id="pnlMessageHolder" Visible="True" runat="server">
  <asp:Label id="lblMessage" runat="server"></asp:Label>
</asp:Panel>
</html>

Introduction to Characters

Getting the Character From its Position in a String

As mentioned already, a string is a combination of symbols or characters. Each character in a string has an indexed position from 1 to its last character. To let you find out what character occupies a certain position inside of a string, the Visual Basic language provides a function named GetChar. Its syntax is:

Public Shared Function GetChar(ByVal str As String,
			       ByVal Index As Integer) As Char

The first argument is the string that will be considered. If you pass this argument as an empty string or Nothing, you would receive an error. The second argument is the position to be considered inside the string. The value must be between 1 and the length of the string. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<title>Strings</title>
</head>
<body>
<%
Dim item As String

item = "Television"

Response.Write("Word: " & item)
Response.Write("<br>The character at position 5 is " & GetChar(item, 5))
%>
</body>
</html>

This would produce:

Getting a Character

To let you access a character based on its position inside a string, the String class is equipped with a member named Chars. To access a character, add some parentheses to the Chars member and pass the position. This time, the positions starts at 0, continues with 1, and so on. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<title>Strings</title>
</head>
<body>
<%
Dim item As String

item = "Television"

Response.Write("Word: " & item)
Response.Write("<br>The character at position 5 is " & item.Chars(4))
%>
</body>
</html>

This would produce:

Getting a Character

The Numeric Code of a Character

To,let you get the numeric code of a character, the String class is equipped with a method named Asc(). Its syntax is:

Public Shared Function Asc(ByVal string As Char) As Integer

The function takes a character as argument. If the function is successful, it returns the numeric equivalent. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<title>Strings</title>
</head>
<body>

<%
Dim Character As Char
Dim Number As Integer

Character = "W"
Number = Asc(Character)

Response.Write("The numeric code for " & Character & " is " & Number)
%>

</body>
</html>

This would produce:

The Asc Function

Character Duplication

To let you have a repeating character in a string, ythe Visual Basic language provides a function named StrDup. This function is provided in two versions whose syntaxes are:

Public Shared Function StrDup(ByVal Number As Integer,
                              ByVal Character As { Char | String }) As String
 - or -
Public Shared Function StrDup(ByVal Number As Integer,
                              ByVal Character As Object) As Object

The second argument is the character that will be duplicated. The first argument specifies the number of times to duplicate it. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<title>Strings</title>
</head>
<body>

<%
Dim Start As Char = "We need your c"
Dim End$ = "peration to expedite this matter."
Dim Result$ = Start & StrDup(2, "o") & End$

Response.Write(Result$)
%>

</body>
</html>

This would produce:

String Duplicate

Converting an Expression to Character

As you may know already, to convert an expression to a character, you can call the CChar() function. Its syntax is:

Function CChar(ByVal Expression As Object) As Char

This function takes a value as argument. The argument must be convertible to a character. If so, the function returns a character.

The ASCII Character of a Number

To help you find the equivalent ASCII character of such a number, the Visual Basic language provides a function named Chr. Its syntax is:

Public Function Chr(ByVal CharCode As Integer) As Char

When calling this function, pass a small number as argument. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<title>Strings</title>
</head>
<body>

<%
Dim Character As Char
Dim Number As Integer

Number = 114
Character = Chr(Number)

Response.Write("The ASCII character of " & Number & " is " & Character)
%>

</body>
</html>

This would produce:

Character

The Wide ASCII Character of a Number

If you pass a number lower than 0 or higher than 255 to the Chr() function, you would receive an error. The reason you may pass a number higher than 255 is that you may want to get a character beyond those of US English, such as . To support such numbers, the Visual Basic language provides another version of the function. Its syntax is:

Public Function ChrW(ByVal CharCode As Integer) As Char

The W here represents Wide Characters. This makes it possible to store the character in the memory equivalent to the Short integer data type, which can hold numbers from -32768 to 32767. Normally, you should consider that the character should fit in a Char data type,, which should be a positive number between 0 and 65535.

Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<title>Strings</title>
</head>
<body>

<%
Dim Character As Char
Dim Number As Short

Number = 358
Character = ChrW(Number)

Response.Write("The ASCII character of " & Number & " is " & Character)
%>

</body>
</html>

This would produce:

Wide Characters

The Length of a String

The length of a string is the number of characters it contains. To assist you with finding the length of a string, the Visual Basic language provides a function named Len. Its syntax is:

Public Shared Function Len(ByVal Expression As String) As Integer

This function expects a string as argument. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<title>Strings</title>
</head>
<body>

<%
Dim Item As String
Dim Length As Integer

Item = "Television"
Length = Len(Item)

Response.Write("The number of characters in """ & Item & """ is " & Length)
%>

</body>
</html>

This would produce:

The Length of a String

As an alternative to let you get this information, the String class is equipped with a property named Length.

 

Primary Operations on Strings

Case Conversion

To let you convert a character or a string to lowercase, the Visual Basic language provides a function named LCase that is overloaded in two versions. Their syntaxes are:

Public Shared Function LCase(ByVal Value As Char) As Char
Public Shared Function LCase(ByVal Value As String) As String

Here is an example:

<script runat="server">
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    Dim rndEmployeeNumber As New Random
    
    txtEmployeeNumber.Text = rndEmployeeNumber.Next(10000, 99999)
    
    If String.IsNullOrEmpty(txtMiddleName.Text) Then
        txtUsername.Text = LCase(txtFirstName.Text & txtLastName.Text)
    Else
      txtUsername.Text = LCase(txtFirstName.Text & txtMiddleName & txtLastName.Text)
    End If
End Sub
</script>

To convert a character, a string or an expression to uppercase, the Visual Basic language provides a function named UCase that also is overloaded with two versions. These functions take one argument as the string or expression to be considered. The syntaxes are:

Public Shared Function UCase(ByVal Value As Char) As Char
Public Shared Function UCase(ByVal Value As String) As String

Besides the UCase() and the LCase() functions, to convert the cases of characters in a string, the Visual Basic language provides the StrConv() function. Its syntax is:

Public Shared Function StrConv(ByVal str As String,
			       ByVal Conversion As Microsoft.VisualBasic.VbStrConv,
			       Optional ByVal LocaleID As Integer,) As String

The first argument of this function is the string whose characters would be converted. The second argument specifies the type of conversion to perform. This argument is a member of the VbStrConv enumeration. From what we have learned so far, this argument can have one of the following values:

  • VbStrConv.None: There will be no conversion
  • VbStrConv.UpperCase: This would have the same effect as the UCase$ function. It converts the first argument's characters to uppercase
  • VbStrConv.LowerCase: This would have the same effect as the LCase$ function. It converts the first argument's characters to lowercase
  • VbStrConv.ProperCase: The first character of each word of the first argument would be converted to uppercase

The last argument is optional. It allows you to specify the language whose rules would be used to control the conversion.

Converting a String to Uppercase or Lowercase

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

Public Function ToUpper As String

To convert a string to lowercase, you can call the String.ToLower() method. Its syntax is:

Public Function ToLower As String

Replacing a Character or a Sub-String in a String

To let you replacing a character or a sub-string in a string, the Visual Basic language provides the Replace() function. Its syntax is:

Public Function Replace(
   ByVal Expression As String,
   ByVal Find As String,
   ByVal Replacement As String,
   Optional ByVal Start As Integer = 1,
   Optional ByVal Count As Integer = -1,
   Optional ByVal Compare As CompareMethod = CompareMethod.Binary
) As String

The first argument is the string on which the operation will be performed. The second argument is the character or string to look for in the Expression. If that character or string is found, the third argument is the character or string to replace it with. Here is an example:

<script runat="server">
Sub btnCreateRecordClick(ByVal sender As Object, ByVal e As EventArgs)
    Dim staff As Employee
    Dim strPhoneNumber As String

    staff = New Employee(txtEmployeeNumber.Text,
        		 txtFirstName.Text, txtLastName.Text)
    staff.MiddleName = txtMiddleName.Text
    staff.Username = txtUsername.Text
    staff.Password = txtPassword.Text
    staff.SocialSecurityNumber = txtSocialSecurityNumber.Text
  
    ' We will format the phone number as 000-000-0000
    ' If there are  empty spaces, remove them
    strPhoneNumber  = Replace(txtPhoneNumber.Text, " ", "")
    ' If there is an opening parenthesis, remove it
    strPhoneNumber  = Replace(strPhoneNumber, "(", "")
    ' If there is a closing parenthesis, replace it with -
    strPhoneNumber  = Replace(strPhoneNumber, ")", "-")

    staff.PhoneNumber = strPhoneNumber

    lblEmployeeNumber.Text = txtEmployeeNumber.Text
    lblEmployeeName.Text = staff.LastName
    lblUsername.Text = staff.Username
    lblPassword.Text = staff.Password
    lblSocialSecurityNumber.Text = staff.SocialSecurityNumber
    lblPhoneNumber.Text = staff.PhoneNumber

    pnlRecord.Visible = True
    pnlApplication.Visible = False
End Sub
</script>

Here is an example of using the webpage:

A Null, Empty, or White-Spaced String

Replacing a Character or a Sub-String in a String

Replacing a Character or a Sub-String in a String

As an alternative, the String class is equipped with the Replace() method that is overloaded with two versions. The version that applies to characters uses the following syntax:

Public Function Replace(oldChar As Char,
			newChar As Char) As String

If you want to remove or replace a sub-string, use the following syntax:

Public Function Replace(oldValue As String,
			newValue As String) As String

Copying a String

After declaring and initializing one string variable, you can assign it to another string variable using the assignment operator. 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 Shared Function Copy(str As String) As String

Copying To a String

The String.Copy() method is used to copy all characters of one string into another string. To let you copy only a few characters, the String class is equipped with a method named CopyTo. Its syntax is:

Public Sub CopyTo(sourceIndex As Integer,
		  destination As Char(),
		  destinationIndex As Integer,
		  count As Integer)

Strings Comparisons

Introduction

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 Visual Basic language provides a function named StrCmp. Its syntax is:

Public Shared Function StrComp(
   ByVal String1 As String,
   ByVal String2 As String,
   <Microsoft.VisualBasic.OptionCompareAttribute>
   Optional ByVal Compare As Microsoft.VisualBasic.CompareMethod
) As Integer

The first and the second arguments to this function are strings and both are required. After the function has performed the comparison, it returns

  • -1 if string1 is less than string2
  •   0 if string1 and string2 are equal
  •   1 if string1 is greater than string2

Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>
<html>
<head>
<title>Exercise</title>
</head>
<body>
<div align="center">
<%
Dim name = "Stanley"
Dim full = "Stan Ley"
Dim first = "Stanley"
Dim great = "stanley"

Dim comparison = StrComp(name, full)
Response.Write("Comparing """ & name & """ with """ & full & """ produces " & comparison)

comparison = StrComp(name, first)
Response.Write("<br>Comparing """ & name & """ with """ & first & """ produces " & comparison)

comparison = StrComp(name, great)
Response.Write("<br>Comparing """ & name & """ with """ & great & """ produces " & comparison)
%>
</body>
</html>

This would produce:

Strings Comparisons

The third argument allows you to specify the comparison in binary or text format. This argument can have one of the following values:

Constant Value Description
vbBinaryCompare 0 Perform a binary comparison
vbTextCompare 1 Perform a textual comparison

Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>
<html>
<head>
<title>Exercise</title>
</head>
<body>
<div align="center">
<%
Dim name = "Stanley"
Dim full = "Stan Ley"
Dim first = "Stanley"
Dim great = "stanley"

Dim comparison = StrComp(name, full, vbTextCompare)
Response.Write("Comparing """ & name & """ with """ & full & """ produces " & comparison)

comparison = StrComp(name, first, vbTextCompare)
Response.Write("<br>Comparing """ & name & """ with """ & first & """ produces " & comparison)

comparison = StrComp(name, great, vbTextCompare)
Response.Write("<br>Comparing """ & name & """ with """ & great & """ produces " & comparison)
%>
</body>
</html>

This would produce:

Strings Comparisons

To support string comparison, the String class is equipped with the Compare() overloaded method. A version of this method uses the following syntax:

Public Shared Function Compare(strA As String,
			       strB As String) As Integer

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 option, the String class proposes another version of the method. Its syntax is:

Public Shared Function Compare(strA As String,
			       strB As String,
			       ignoreCase As Boolean) As Integer

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

String Equality

To let you compare two strings for equality, the String class is equipped with the overloaded Equals() method. When calling it, pass a string variable that calls it. 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:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<script runat="server">
Sub btnSubmitClick(ByVal sender As Object, ByVal e As EventArgs)
    Dim original As String
    Dim confirm As String

    original = txtNewPassword.Text
    confirm = txtConfirmPassword.Text

    If original.Equals(confirm) = True Then
        lblMessage.Text = "The passwords match."
    Else
        lblMessage.Text = "The passwords don't match."
    End If
End Sub
</script>
<title>Online Store</title>
</head>
<body>
<h4>Online Store</h4>

<form id="frmValidation" runat="server"> <div>
<table>
  <tr>
    <td>New Password:</td>
    <td>
        <asp:TextBox id="txtNewPassword" runat="server"></asp:TextBox>
      </td>
  </tr>
  <tr>
    <td>Confirm Password:</td>
    <td>
        <asp:TextBox id="txtConfirmPassword" runat="server"></asp:TextBox>
      </td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td>
        <asp:Button id="btnSubmit" OnClick="btnSubmitClick" Text="Submit" runat="server"></asp:Button>
      </td>
  </tr>
</table>

<p style="text-align: center"><asp:Label id="lblMessage" runat="server"></asp:Label></p>
</div>
</form>
</body>
</html>

Here is an example of running the program:

Equality of Two Strings Equality of Two Strings
   
Equality of Two Strings Equality of Two Strings

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

Public Shared Function Equals(a As String,
			      b As String,
			      comparisonType As StringComparison) As Boolean

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

Public Shared Function Equals(a As String,
			      b As String) As Boolean

This method considers the cases of the characters. If you don't want this option taken into consideration, use the following version of the method:

Public Function Equals(value As String,
		       comparisonType As StringComparison) As Boolean

Remember that the String.Equals() method is just a class-based implementation of the = operator.

Character and String Conversions

Introduction

As you may know already, to convert an expression to a string, you can call the CStr() function. Its syntax is:

Public Function CStr(ByVal Expression As Object) As String

The argument can be almost any expression but the compiler has to be able to convert it to a string, which in most cases it can. If it is successful, the function returns a string. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<script runat="server">
Public Class Rhombus
    Private len As Double
    Private hgt As Double

    Public Sub New(ByVal length As Double, ByVal height As Double)
        len = length
        hgt = height
    End Sub

    Public Property Length As Double
        Get
            Return len
        End Get
        Set(value As Double)
            len = value
        End Set
    End Property

    Public Property Height As Double
        Get
            Return hgt
        End Get
        Set(value As Double)
            hgt = value
        End Set
    End Property

    Public ReadOnly Property Area As Double
        Get
            Return len * hgt / 2.0
        End Get
    End Property
End Class

Public Class Rhombohedron
    Private dp As Double
    Private bs As Rhombus

    Public Sub New(ByVal base As Rhombus, ByVal length As Double)
        bs = base
        dp = length
    End Sub

    Public Property Depth As Double
        Get
            Return dp
        End Get
        Set(value As Double)
            dp = value
        End Set
    End Property

    Public Property Base As Rhombus
        Get
            Return bs
        End Get
        Set(value As Rhombus)
            bs = value
        End Set
    End Property

    Public ReadOnly Property FaceArea As Double
        Get
            Return bs.Area
        End Get
    End Property

    Public ReadOnly Property Volume As Double
        Get
            Return bs.Area * dp
        End Get
    End Property
End Class

Sub btnCalculateClick(ByVal sender As Object, ByVal e As EventArgs)
        Dim p As Double
        Dim q As Double
        Dim d As Double
        Dim v As Double
        Dim r As Rhombus
        Dim rh As Rhombohedron

        p = txtLength.Text
        q = txtHeight.Text
        d = txtDepth.Text

        rh = New Rhombohedron(New Rhombus(p, q), d)

        lblLength.Text = CStr(p)
        lblHeight.Text =  CStr(q)
        lblDepth.Text =  CStr(d)
        lblFaceArea.Text =  CStr(rh.FaceArea)
        lblVolume.Text =  CStr(rh.Volume)

        pnlRhombohedron.Visible = False
        pnlResults.Visible = True
End Sub
</script>
<style>
#main-title
{
    font-size: 1.08em;
    font-weight: bold;
    text-align: center;
    font-family: Georgia, Garamond, 'Times New Roman', Times, serif;
}
.tblRhombohedron { width: 200px; }
#whole
{
    margin: auto;
    width:  205px;
}
</style>
<html>
<head runat="server">
    <title>Geometric Volumes - Rhombohedron</title>
</head>
<body>
    <p id="main-title">Geometric Volumes - Rhombohedron</p>
    <form id="frmRhombohedron" runat="server">
    <div id="whole">
 
<asp:Panel id="pnlRhombohedron" Visible="true" runat="server">
    <h3>Base</h3>
<table class="tblRhombohedron">
  <tr>
    <td>Length:</td>
    <td><asp:TextBox id="txtLength" Width="75px" runat="server" /></td>
    </tr>
    <tr>
      <td>Height:</td>
      <td><asp:TextBox id="txtHeight" runat="server" Width="75px" /></td>
    </tr>
</table>
<h3>Prism</h3>
<table class="tblRhombohedron">
  <tr>
    <td>Depth:</td>
    <td><asp:TextBox id="txtDepth" Width="75px" runat="server" /></td>
  </tr>
  <tr>
      <td>&nbsp;</td>
      <td><asp:Button id="btnCalculate" runat="server"
                      Text="Calculate" Width="85px" OnClick="BtnCalculateClick" />
      </td>
  </tr>
</table>
</asp:Panel>
 
<asp:Panel id="pnlResults" Visible="false" runat="server">
<table class="tblRhombohedron">
  <tr>
    <td>Length:</td>
    <td><asp:Label id="lblLength" Width="75px" runat="server" /></td>
  </tr>
  <tr>
    <td>Height:</td>
    <td><asp:Label id="lblHeight" runat="server" Width="75px" /></td>
  </tr>
  <tr>
    <td>Depth:</td>
    <td><asp:Label id="lblDepth" runat="server" Width="75px" /></td>
  </tr>
  <tr>
    <td>Face Area: </td>
    <td><asp:Label id="lblFaceArea" runat="server" Width="75px" /></td>
  </tr>
  <tr>
    <td>Volume: </td>
    <td><asp:Label id="lblVolume" runat="server" Width="75px" /></td>
  </tr>
</table>
</asp:Panel>
</div>
</form>
</body>
</html>

The CStr() function is used to convert any type of value to a string. If the value to be converted is a number, you can use the Str() function. Its syntax is:

Public Shared Function Str(ByVal Number As Object) As String

This function expects a number as argument.

Numeric Hexadecimal Conversion

To let you convert a decimal number to its hexadecimal format, the Visual Basic language provides the Hex() function. Its syntax is:

Public Shared Function Hex(
   ByVal Number As { Byte | SByte | Short | UShort |
   Integer | UInteger | Long | ULong | Object } ) As String

Numeric Octal Conversion

To let you convert a decimal number to its octal format, the Visual Basic language provides the Oct() function. Its syntax is:

Public Shared Function Oct(
   ByVal Number As { Byte | SByte | Short | UShort | 
   Integer | UInteger | Long | ULong | Object } ) As String

The Sub-Strings of a String

Introduction to Sub-Strings

A sub-string is a character or a group of characters or symbols that are part of an existing string. As one way to support strings, the String class is equipped with a method named Substring that comes with two versions. One of them uses the following syntax:

Public Function Substring(ByVal startIndex As Integer) As String

The argument specifies the index from where to start building the sub-string up to the end of the string. The other version of the method uses the following syntax:

Public Function Substring(ByVal startIndex As Integer,
			  ByVal length As Integer) As String

The first argument is the same as that of the first version of the method. The second argument specifies the number of characters to consider.

Looking for a Character or a Sub-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 Function Contains(value As String) As Boolean

The Left Sub-String of a String

To derive a string from the left characters of an existing string, you can use a function named Left. Its syntax is:

Public Shared Function Left(ByVal str As String,
			    ByVal Length As Integer) As String

The first argument is the existing string. The second argument is the number of characters counted from the left side of the string. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>
<html>
<head>
<script runat="server">
Public Class Employee
        Public EmployeeNumber As String
        Public FirstName As String
        Public MiddleName As String
        Public MI As Char
        Public LastName As String
        Public Username As String
        Public Password As String
        Public SocialSecurityNumber As String
        Public PhoneNumber As String

        Public Sub New(ByVal emplNumber As String,
                       ByVal fName As String, ByVal lName As String)
            EmployeeNumber = emplNumber
            FirstName = fName
            LastName = lName
        End Sub
End Class

Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    Dim mi As Char

    Dim rndEmployeeNumber As New Random

    txtEmployeeNumber.Text = rndEmployeeNumber.Next(10000, 99999)

    If String.IsNullOrWhiteSpace(txtMiddleName.Text) Then
        mi = ""
     txtUsername.Text = LCase(Left(txtFirstName.Text, 1) & Left(txtLastName.Text, 5))
    Else
        mi = Left(txtMiddleName.Text, 1)
txtUsername.Text = LCase(Left(txtFirstName.Text, 1) & mi & Left(txtLastName.Text, 5))
    End If
End Sub

Sub btnCreateRecordClick(ByVal sender As Object, ByVal e As EventArgs)
    Dim mi As Char

    Dim staff As Employee
    Dim strPhoneNumber As String

    staff = New Employee(txtEmployeeNumber.Text,
                     txtFirstName.Text, txtLastName.Text)
    staff.MiddleName = txtMiddleName.Text
    staff.MI = mi
    staff.Username = txtUsername.Text
    staff.Password = txtPassword.Text
    staff.SocialSecurityNumber = txtSocialSecurityNumber.Text

    ' We will format the phone number as 000-000-0000
    ' If there are  empty spaces, remove them
    strPhoneNumber = Replace(txtPhoneNumber.Text, " ", "")
    ' If there is an opening parenthesis, remove it
    strPhoneNumber = Replace(strPhoneNumber, "(", "")
    ' If there is a closing parenthesis, replace it with -
    strPhoneNumber = Replace(strPhoneNumber, ")", "-")

    staff.PhoneNumber = strPhoneNumber

    lblEmployeeNumber.Text = txtEmployeeNumber.Text

    If String.IsNullOrWhiteSpace(txtMiddleName.Text) Then
        mi = ""
        lblEmployeeName.Text = txtFirstName.Text & " " & txtLastName.Text
    Else
        mi = Left(txtMiddleName.Text, 1)
 lblEmployeeName.Text = txtFirstName.Text & " " & mi & ". " & " " & txtLastName.Text
    End If

    lblUsername.Text = staff.Username
    lblPassword.Text = staff.Password
    lblSocialSecurityNumber.Text = staff.SocialSecurityNumber
    lblPhoneNumber.Text = staff.PhoneNumber

    pnlRecord.Visible = True
    pnlApplication.Visible = False
End Sub
</script>
<title>Department Store - Employment Application</title>
</head>
<body>
<div align="center">
<h3>Department Store - Employment Application</h3>

<form id="frmEmploymentApplication" runat="server">
<asp:Panel id="pnlApplication" Visible="True" runat="server">
<table>
  <tr>
    <td>Employee #:</td>
    <td><asp:TextBox id="txtEmployeeNumber" runat="server" /></td>
  </tr>
  <tr>
    <td>First Name:</td>
    <td><asp:TextBox id="txtFirstName" AutoPostBack="True" runat="server" /></td>
  </tr>
  <tr>
    <td>Middle Name:</td>
    <td><asp:TextBox id="txtMiddleName" AutoPostBack="True" runat="server" /></td>
  </tr>
  <tr>
    <td>Last Name:</td>
    <td><asp:TextBox id="txtLastName" AutoPostBack="True" runat="server" /></td>
  </tr>
    <tr>
    <td>Social Security #:</td>
    <td><asp:TextBox id="txtSocialSecurityNumber" runat="server" /></td>
  </tr>
  <tr>
    <td>Phone Number:</td>
    <td><asp:TextBox id="txtPhoneNumber" runat="server" /></td>
  </tr>
    <tr>
    <td>Username:</td>
    <td><asp:TextBox id="txtUsername" runat="server" /></td>
  </tr>
  <tr>
    <td>Password:</td>
    <td><asp:TextBox id="txtPassword" AutoPostBack="True"
    		     Text="Password1" runat="server" /></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td><asp:Button id="btnCreateEmployeeRecord"
                    text="Create Employee Record"
                    OnClick="btnCreateRecordClick"
                    runat="server"></asp:Button> </td>
  </tr>
</table>
</asp:Panel>

<asp:Panel id="pnlRecord" Visible="False" runat="server">
<table>
  <tr>
    <td>Employee #:</td>
    <td><asp:Label id="lblEmployeeNumber" runat="server" /></td>
  </tr>
  <tr>
    <td>Employee Name:</td>
    <td><asp:Label id="lblEmployeeName" runat="server" /></td>
  </tr>
  <tr>
    <td>Social Security #:</td>
    <td><asp:Label id="lblSocialSecurityNumber" runat="server" /></td>
  </tr>
  <tr>
    <td>Phone Number:</td>
    <td><asp:Label id="lblPhoneNumber" runat="server" /></td>
  </tr>
  <tr>
    <td>Username:</td>
    <td><asp:Label id="lblUsername" runat="server" /></td>
  </tr>
  <tr>
    <td>Password:</td>
    <td><asp:Label id="lblPassword" runat="server" /></td>
  </tr>
</table>
</asp:Panel>
</form>
</div>
</body>

<asp:Panel id="pnlMessageHolder" Visible="True" runat="server">
  <asp:Label id="lblMessage" runat="server"></asp:Label>
</asp:Panel>
</html>

Here is an example of using the webpage:

The Left Sub-String of a String

The Left Sub-String of a String

The Left Sub-String of a String

The Left Sub-String of a String

The Left Sub-String of a String

The Left Sub-String of a String

The Left Sub-String of a String

The Left Sub-String of a String

The Right Sub-String of a String

To create a new string using one or more characters from the right side of an existing string, call a function named Right. Its syntax is:

Public Shared Function Right(ByVal str As String, ByVal Length As Integer) As String

The first argument is the original string. The second argument is the number of characters counted from the right side of the string. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>
<html>
<head>
<script runat="server">
Public Class Employee
        Public EmployeeNumber As String
        Public FirstName As String
        Public MiddleName As String
        Public MI As Char
        Public LastName As String
        Public Username As String
        Public Password As String
        Public SocialSecurityNumber As String
        Public PhoneNumber As String

        Public Sub New(ByVal emplNumber As String,
                       ByVal fName As String, ByVal lName As String)
            EmployeeNumber = emplNumber
            FirstName = fName
            LastName = lName
        End Sub
End Class

Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    Dim mi As Char

    Dim rndEmployeeNumber As New Random

    txtEmployeeNumber.Text = rndEmployeeNumber.Next(10000, 99999)

    If String.IsNullOrWhiteSpace(txtMiddleName.Text) Then
        mi = ""
     txtUsername.Text = LCase(Left(txtFirstName.Text, 1) & Left(txtLastName.Text, 5))
    Else
        mi = Left(txtMiddleName.Text, 1)
txtUsername.Text = LCase(Left(txtFirstName.Text, 1) & mi & Left(txtLastName.Text, 5))
    End If
End Sub

Sub btnCreateRecordClick(ByVal sender As Object, ByVal e As EventArgs)
    Dim mi As Char

    Dim staff As Employee
    Dim strPhoneNumber As String

    staff = New Employee(txtEmployeeNumber.Text,
                     txtFirstName.Text, txtLastName.Text)
    staff.MiddleName = txtMiddleName.Text
    staff.MI = mi
    staff.Username = txtUsername.Text
    staff.Password = txtPassword.Text
    staff.SocialSecurityNumber = txtSocialSecurityNumber.Text

    ' We will format the phone number as 000-000-0000
    ' If there are  empty spaces, remove them
    strPhoneNumber = Replace(txtPhoneNumber.Text, " ", "")
    ' If there is an opening parenthesis, remove it
    strPhoneNumber = Replace(strPhoneNumber, "(", "")
    ' If there is a closing parenthesis, replace it with -
    strPhoneNumber = Replace(strPhoneNumber, ")", "-")

    staff.PhoneNumber = strPhoneNumber

    lblEmployeeNumber.Text = txtEmployeeNumber.Text

    If String.IsNullOrWhiteSpace(txtMiddleName.Text) Then
        mi = ""
        lblEmployeeName.Text = txtFirstName.Text & " " & txtLastName.Text
    Else
        mi = Left(txtMiddleName.Text, 1)
 lblEmployeeName.Text = txtFirstName.Text & " " & mi & ". " & " " & txtLastName.Text
    End If

    lblUsername.Text = staff.Username
    lblPassword.Text = staff.Password
    lblSocialSecurityNumber.Text = staff.SocialSecurityNumber
    lblLast4DigitsOfSSN.Text = Right(staff.SocialSecurityNumber, 4)
    lblPhoneNumber.Text = staff.PhoneNumber

    pnlRecord.Visible = True
    pnlApplication.Visible = False
End Sub
</script>
<title>Department Store - Employment Application</title>
</head>
<body>
<div align="center">
<h3>Department Store - Employment Application</h3>

<form id="frmEmploymentApplication" runat="server">
<asp:Panel id="pnlApplication" Visible="True" runat="server">
<table>
  <tr>
    <td>Employee #:</td>
    <td><asp:TextBox id="txtEmployeeNumber" runat="server" /></td>
  </tr>
  <tr>
    <td>First Name:</td>
    <td><asp:TextBox id="txtFirstName" AutoPostBack="True" runat="server" /></td>
  </tr>
  <tr>
    <td>Middle Name:</td>
    <td><asp:TextBox id="txtMiddleName" AutoPostBack="True" runat="server" /></td>
  </tr>
  <tr>
    <td>Last Name:</td>
    <td><asp:TextBox id="txtLastName" AutoPostBack="True" runat="server" /></td>
  </tr>
    <tr>
    <td>Social Security #:</td>
    <td><asp:TextBox id="txtSocialSecurityNumber" runat="server" /></td>
  </tr>
  <tr>
    <td>Phone Number:</td>
    <td><asp:TextBox id="txtPhoneNumber" runat="server" /></td>
  </tr>
    <tr>
    <td>Username:</td>
    <td><asp:TextBox id="txtUsername" runat="server" /></td>
  </tr>
  <tr>
    <td>Password:</td>
    <td><asp:TextBox id="txtPassword" AutoPostBack="True"
    		     Text="Password1" runat="server" /></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td><asp:Button id="btnCreateEmployeeRecord"
                    text="Create Employee Record"
                    OnClick="btnCreateRecordClick"
                    runat="server"></asp:Button> </td>
  </tr>
</table>
</asp:Panel>

<asp:Panel id="pnlRecord" Visible="False" runat="server">
<table>
  <tr>
    <td>Employee #:</td>
    <td><asp:Label id="lblEmployeeNumber" runat="server" /></td>
  </tr>
  <tr>
    <td>Employee Name:</td>
    <td><asp:Label id="lblEmployeeName" runat="server" /></td>
  </tr>
  <tr>
    <td>Social Security #:</td>
    <td><asp:Label id="lblSocialSecurityNumber" runat="server" /></td>
  </tr>
  <tr>
    <td>Last 4 Digits of SSN:</td>
    <td><asp:Label id="lblLast4DigitsOfSSN" runat="server" /></td>
  </tr
  <tr>
    <td>Phone Number:</td>
    <td><asp:Label id="lblPhoneNumber" runat="server" /></td>
  </tr>
  <tr>
    <td>Username:</td>
    <td><asp:Label id="lblUsername" runat="server" /></td>
  </tr>
  <tr>
    <td>Password:</td>
    <td><asp:Label id="lblPassword" runat="server" /></td>
  </tr>
</table>
</asp:Panel>
</form>
</div>
</body>

<asp:Panel id="pnlMessageHolder" Visible="True" runat="server">
  <asp:Label id="lblMessage" runat="server"></asp:Label>
</asp:Panel>
</html>

Here is an example of using the webpage:

The Left Sub-String of a String

The Left Sub-String of a String

The Left Sub-String of a String

The Left Sub-String of a String

The Left Sub-String of a String

The Left Sub-String of a String

The Left Sub-String of a String

The Left Sub-String of a String

The Mid Sub-String of a String

You may want to create a string using some characters either from the left, from the right, or from somewhere inside an existing string. To assist you with this, the Visual Basic language provides a function named Mid. Its syntax is:

<%@ Page Language="VB" %>

<!DOCTYPE html>

<html>
<head runat="server">
<title>Exercise</title>
</head>
<body>
<%
Dim programmingEnvironment As String

programmingEnvironment = "Microsoft Visual Basic"

Response.Write("The " & Mid(programmingEnvironment, 10, 13) & " language")
%>
</body>
</html>

This would produce:

Mid

Finding a Sub-String

To help you find out whether a string contains a certain character or a certain contiguous group of characters, the Visual Basic language provides the InStr() function. It is overloaded with two versions whose syntaxes are:

Public Shared Function InStr(
   ByVal String1 As String,
   ByVal String2 As String,
   Optional ByVal Compare As CompareMethod) As Integer
 -or-
Public Shared Function InStr(
   ByVal Start As Integer,
   ByVal String1 As String,
   ByVal String2 As String,
   Optional ByVal Compare As Microsoft.VisualBasic.CompareMethod
) As Integer

In the first version of the function, the String1 argument is the string on which the operation will be performed. The String2 argument is the character or the sub-string to look for. If String2 is found in String1 (as part of String1), the function return the position of the first character. Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>
<html>
<head>
<title>Exercise</title>
</head>
<body>
<%
Dim programmingEnvironment As String

programmingEnvironment = "the Visual Basic Computer Language"

Response.Write("In " & programmingEnvironment &
	       ", ""Basic"" is found at position " &
               InStr(programmingEnvironment, "Basic"))
%>
</body>
</html>

This would produce:

In String

The InStr() function is used to start checking a string from the left side. If you want to start checking from the right side, call the InStrRev() function. Its syntax is:

Public Function InStrRev(
   ByVal StringCheck As String,
   ByVal StringMatch As String,
   Optional ByVal Start As Integer = -1,
   Optional ByVal Compare As CompareMethod = CompareMethod.Binary
) As Integer

Other Operations on Strings

Reversing a String

To let you reverse a string, the Visual Basic language provides the StrReverse() function. Its syntax is:

Public Function StrReverse(ByVal Expression As String) As String

Here is an example:

<%@ Page Language="VB" %>

<!DOCTYPE html>
<html>
<head>
<title>Exercise</title>
</head>
<body>
<%
Dim StrValue As String
Dim StrRev As String

StrValue = "Equatorial Guinea"
StrRev = StrReverse(strValue)

Response.Write(StrValue & "<br>" & StrRev)
%>
</body>
</html>

This would produce:

String Reverse

Because the StrReverse() function returns a string, you can write it as StrReverse$.

Trimming a String

To remove all empty spaces from the left side of a string, you can call the LTrim() function. Its syntax is:

Public Shared Function LTrim(ByVal str As String) As String

To remove all empty spaces from the right side of a string, you can call the RTrim() function. Its syntax is:

Public Shared Function RTrim(ByVal str As String) As String

To remove the empty spaces from both sides of a string, you can call the Trim() function. Its syntax is:

Public Shared Function Trim(ByVal str As String) As String
Public