Home

Strings

 

Introduction to Strings

 

Introduction

As seen in Lesson 3, a string is one or a combination of characters. To declare a variable for it, you can use either the String or the Object data types. To initialize the variable, put its value in double-quotes and assign it to the variable. Here are examples:

<%@ Page Language="VB" %>

<html>
<head>

<title>Exercise</title>

</head>
<body>

<%
Dim FirstName As Object
Dim LastName As String

FirstName = "William"
LastName = "Sansen"
%>

</body>

String Concatenation

As seen in Lesson 2, string concatenation consists of adding one string to another. to support this operation, you can use either the + or the & operator. Here are examples:

<%@ Page Language="VB" %>

<html>
<head>

<title>Exercise</title>

</head>
<body>

<%
Dim FirstName As Object
Dim LastName As String
Dim FullName As String

FirstName = "William"
LastName = "Sansen"
FullName  = LastName + ", " & FirstName

Response.Write("Full Name: " & FullName)
%>

</body>

This would produce:

String

If you have many strings to add to a primary string, you can use either the += or the &= operator. Here is an example:

<%@ Page Language="VB" %>

<html>
<head>

<title>Exercise</title>

</head>
<body>

<%
        Dim FullName As String

        FullName  = "Sansen"
        FullName += ", "
        FullName += "William"

        Response.Write("Full Name: " & FullName)
%>

</body>

Introduction to Characters

 

Character Duplication

In Lesson 3, we had a brief introduction to strings. We learned that a string was a combination of characters.

From our knowledge of using the computer, we know that, to create a string, we can press the desired characters on the keyboard. An example of a string would be: "Production". To have a repeating character in a string, you can press its key as many times as you want. For example, in "cooperation", you would press o twice. To programmatically perform such an operation, that is, to duplicate a character in a string, you can call the StrDup() function. 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" %>

<html>
<head>

<title>Exercise</title>

</head>
<body>

<%
    Dim Start As Char = "We need your c"
    Dim End$ = "peration to expedite this matter"
    Dim Result$

    Result$ = Start & StrDup(2, "o") & End$

    Response.Write(Result$)
%>

</body>

This would produce:

String

Expression Character Conversion

If you have such a string, you may be interested in the individual characters it contains. In Lesson 3, we also saw that, 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.

Getting the ASCII Character of a Number

The characters used in the US English and the most common characters of Latin-based languages are created in a list or map of character codes. Each character is represented with a small number between 0 and 255. This means that each character must fit in a byte.

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" %>

<html>
<head>

<title>Exercise</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>

This would produce:

String

Besides finding the ASCII equivalent of a number, the Chr() function can be used to apply some behavior in a program. For example, a combination of Chr(13) and Chr(10) would break a line in an expression, which is equivalent to the vbCrLf operator.

Getting 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 Character. 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" %>

<html>
<head>

<title>Exercise</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>

This would produce:

The Length of a String

One of the most fundamental characteristics of a string is the number of characters it contains. This number is referred to as the length of a string. 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. If the function succeeds in counting the number of characters, which it usually does, it returns the an integer. Here is an example:

<%@ Page Language="VB" %>

<html>
<head>

<title>Exercise</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>

This would produce:

String

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 creating the procedure, enter the argument and its name in the parentheses of the procedure. Then, in the body of the procedure, use the argument as you see fit. Here is an example:

<script language="vbscript" type="text/vbsscript" runat="server">

Private Sub Show(ByVal Gdr As Char)
        Response.Write(Gdr)
    End Sub

End Module

When calling the procedure, you can pass a value for the argument in double-quotes. Here is an example:

<%@ Page Language="VB" %>

<html>
<head>
<script language="vbscript" type="text/vbsscript" runat="server">

Private Sub Show(ByVal Sex As Char)
        Response.Write(Sex)
End Sub

</script>

<title>Exercise</title>

</head>
<body>

<%
    Show("F")
%>

</body>

This would produce:

String

In the same way, you can apply any of the features we studied for procedures, including passing as many arguments as you want or passing a mixture of characters, strings, and other types of arguments. You can also create a procedure that receives an optional argument.

Returning a Character or a String From a Function

To create a function that returns a character or a string, create the procedure using the Function keyword and, on the right side of the parentheses, include the Char or String data type preceded by the As keyword. Here is an example we saw in Lesson 5:

<script language="vbscript" type="text/vbsscript" runat="server">

Function GetFullName$()
        Dim FirstName$, LastName$

        FirstName = InputBox("Enter First Name: ")
        LastName = InputBox("Enter Last Name: ")

        Return LastName & ", " & FirstName
End Function

</script>

When calling the function, you can use it as a normal procedure or you can retrieve the value it returns and use it as you see fit.

The Characters of a String

 

Getting the Character From its Position in a String

As mentioned already, a string is a combination of symbols or characters. An example is "Television". Each character in a string has an indexed position from 1 to its last character:

T e l e v i s i o n
1 2 3 4 5 6 7 8 9 10

To find out what character occupies a certain position inside of a string, you can call the GetChar() function. 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 consider inside the string. The value must be between 1 and the length of the string. Here is an example:

<%@ Page Language="VB" %>

<html>
<head>

<title>Exercise</title>

</head>
<body>

<%
        Dim Item As String

        Item = "Television"

        Response.Write("The character at position 5 is " & GetChar(Item, 5))
%>

</body>

This would produce:

String

Getting the ASCII Numeric Equivalent of a Character

If you have a character and want to find its equivalent character, you can call the Asc() function. Its syntax is:

Public Overloads Function Asc(ByVal String As Char) As Integer

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

<%@ Page Language="VB" %>

<html>
<head>

<title>Exercise</title>

</head>
<body>

<%
        Dim Character As Char
        Dim Number As Integer

        Character = "W"
        Number = Asc(Character)

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

</body>

This would produce:

String

Character and String Conversions

 

Introduction

In Lesson 3, we saw that, 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" %>

<html>
<head>

<title>Exercise</title>

</head>
<body>

<%
        Dim DateHired As Date

        DateHired = #1/4/2005#

        Response.Write("Date Hired: " & CStr(DateHired))
%>

</body>

This would produce:

String

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

<%@ Page Language="VB" %>

<html>
<head>

<title>Exercise</title>

</head>
<body>

<%
        Dim Number As Double

        Number = 1450.5 / 2

        Response.Write("1450.50 / 2 =  " & Str(Number))
%>

</body>

This would produce:

String

Numeric Hexadecimal Conversion

In Lesson 3, we saw that the Visual Basic language supports hexadecimal number and we saw how to initialize an integer variable with a hexadecimal number. Now, on the other hand, if you have a decimal number but need it in hexadecimal format, you can convert it. To support this operation, you can call the Hex() function. Its syntax is:

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

This function is used to convert either an integer-based or a decimal number to its hexadecimal equivalent. It returns the result as a string. Here is an example:

<%@ Page Language="VB" %>

<html>
<head>

<title>Exercise</title>

</head>
<body>

<%
        Dim Number As UInteger

        Number = 286345
        Response.Write(CStr(Number) & " in hexadecimal format is " & Hex(Number))
%>

</body>

This would produce:

String

Numeric Octal Conversion

If you have a decimal number you want to convert to its octal format, you can call the Oct() function. Its syntax is:

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

This function takes an integer-based or a decimal number and converts its octal equivalent. It returns the result as a string. Here is an example:

<%@ Page Language="VB" %>

<html>
<head>

<title>Exercise</title>

</head>
<body>

<%
        Dim Number As Integer

        Number = 286345
        Response.Write(CStr(Number) & " in octal format is " & Oct(Number))
%>

</body>

This would produce:

String

Case Conversion

If you are presented with a string or an expression whose cases must be the same, you can convert all of its characters in either uppercase or lowercase.

To convert a character, a string or an expression to uppercase, you can call the UCase() function. 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

The first version receives a character as argument. If the character is already in uppercase, it would be returned the same. If the character is not a readable character, no conversion would happen and the function would return it. If the character is in lowercase, it would be converted to uppercase and the function would then return the uppercase equivalent.

The second version considers the argument supplied as a string. Any letter that is in lowercase in the string would be converted to uppercase. Any letter that is in uppercase would be preserved and would not be changed. Any non-alphabetic character in the string would be kept "as is".

Here is an example:

<%@ Page Language="VB" %>

<html>
<head>

<title>Exercise</title>

</head>
<body>

<%
        Dim ProgrammingEnvironment As String

        ProgrammingEnvironment = "Microsoft Visual Basic 2008 Express Edition"

        Response.Write(UCase(ProgrammingEnvironment))
%>

</body>

To convert a character or a string to lowercase, you can call the LCase() function. It is overloaded in two versions whose syntaxes are:

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

The first version receives a character as argument. If the character is not a readable symbol, it would be kept "as is". If the character is in lowercase, it would not be converted. If the character is in uppercase, it would be converted to lowercase.

The second version of the function receives a string as argument. Any letter in uppercase in the string would be converted to lowercase. Any letter that is in lowercase would not be changed. Any non-alphabetic character in the string would be kept "as is".

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

This function produces a string. The first argument of this function is the string whose characters would be converted. The second argument specifies what type of conversion will be performed. 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. Here is an example:
     
    <%@ Page Language="VB" %>
    
    <html>
    <head>
    
    <title>Exercise</title>
    
    </head>
    <body>
    
    <%
        Dim ProgrammingEnvironment As String
         Dim Result$
    
        ProgrammingEnvironment = "Microsoft Visual Basic 2008 Express Edition"
        Result$ = StrConv$(ProgrammingEnvironment, VbStrConv.Uppercase)
    
        Response.Write(Result$)
    %>
    
    </body>
  • 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. Here is an example:
     
    <%@ Page Language="VB" %>
    
    <html>
    <head>
    
    <title>Exercise</title>
    
    </head>
    <body>
    
    <%
        Dim MCQ$
        Dim Result$
    
        MCQ$ = "multiple choice question examination"
        Result$ = StrConv$(MCQ$, VbStrConv.ProperCase)
    
        Response.Write(Result$)
    %>
    
    </body>

The last argument is optional. It allows you to specify that language whose rules would be used to direct the conversion. By default, the compiler refers to the language of the operation system. In most computers in the United States, this would be US English. If for some reason, you would like to apply different rules, specify its language as the third argument.

 
 
 
 

The Sub-Strings of a String

 

Introduction

A sub-string is a character or a group of characters or symbols that are part of an existing string. The Visual Basic language provides functions to create, manipulate or manage sub-strings. The primary rule to keep in mind is that a sub-string is part of, and depends on, a string. In other words, you cannot have a sub-string if you do  not have a string in the first place.

The Left Sub-String of a String

If you have an existing string but want to create a new string using a number of characters from the left side characters of the string, you can use the Left() function. Its syntax is:

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

The function takes two arguments and both are required. 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" %>

<html>
<head>

<title>Exercise</title>

</head>
<body>

<%
        Dim Process As String

        Process = "learning"

        Response.Write("To " & Left(Process, 5) & " is to gain understanding")
%>

</body>

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

Both arguments are required. 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" %>

<html>
<head>

<title>Exercise</title>

</head>
<body>

<%
        Dim ProgrammingEnvironment As String

        ProgrammingEnvironment = "Microsoft Visual Basic"

        Response.Write("Q" & Right(ProgrammingEnvironment, 5) & " in MS DOS 5.2")
%>

</body>  

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" %>

<html>
<head>

<title>Exercise</title>

</head>
<body>

<%
        Dim ProgrammingEnvironment As String

        ProgrammingEnvironment = "Microsoft Visual Basic 2008 Express Edition"

        Response.Write("The " & Mid(ProgrammingEnvironment, 10, 13) & " language")
%>

</body>

Finding a Sub-String

One of the most regular operations you will perform on a string consists of finding out whether it contains a certain character or a certain contiguous group of characters. To help you with this operation, 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" %>

<html>
<head>

<title>Exercise</title>

</head>
<body>

<%
        Dim ProgrammingEnvironment As String

        ProgrammingEnvironment = "Microsoft Visual Basic Express Edition"

        Response.Write("In " & ProgrammingEnvironment & ", ""Basic"" is found at position " & _
                     InStr(ProgrammingEnvironment, "Basic"))
%>

</body>

The first version of the function asks the interpreter to check String1 from the left looking for String2. If String1 contains more than one instance of String2, the function returns (only) the position of the first instance. Any other subsequent instance would be ignored. If you want to skip the first instance or want the interpreter to start checking from a position other than the left character, use the second version. In this case, the Start argument allows you to specify the starting position from where to start looking for String2 in String1.

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

Replacing a Character or a Sub-String in a String

After finding a character or a sub-string inside of a string, you can take action on it. One of the operations you can perform consists of replacing that character or that sub-string with another character or a sub-string. To do this, 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:

<%@ Page Language="VB" %>

<html>
<head>

<title>Exercise</title>

</head>
<body>

<%
        Dim ProgrammingEnvironment As String

        ProgrammingEnvironment = "Microsoft Visual Basic 2008 Express Edition"

        Response.Write(Replace(ProgrammingEnvironment, "Basic", "C++"))
%>

</body>

Other Operations on Strings

 

Reversing a String

Once a string has been initialized, one of the operations you can perform on it consists of reversing it. To do this, you can call the StrReverse() function. Its syntax is:

Public Function StrReverse(ByVal Expression As String) As String

This function takes as argument the string that needs to be reversed. After performing its operation, the function returns a new string made of characters in reverse order.  Here is an example:

<%@ Page Language="VB" %>

<html>
<head>

<title>Exercise</title>

</head>
<body>

<%
    Dim StrValue As String
    Dim StrRev As String

    StrValue = "République d'Afrique du Sud"
    StrRev = StrReverse(strValue)

    Response.Write(StrValue & vbCrLf & StrRev)
%>

</body>

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

Strings and Empty Spaces

The simplest string is probably one that you declared and initialized. In some other cases, you may work with a string that you must first examine. For example, for some reason, a string may contain an empty space to its left or to its right. If you simply start performing a certain operation on it, the operation may fail. One of the first actions you can take on a string would consist of deleting the empty space(s), if any on its sides.

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

Creating an Empty Spaced String

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

This function is the programmatic equivalent to pressing the Space bar when typing a string to insert an empty space between two characters.

Strings Comparisons

To compare two strings, you can call the StrCmp() function. 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

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:

Private Sub cmdCreate_Click()
    Dim strValue1 As String
    Dim strValue2 As String
    Dim iComparisonValue
    
    strValue1 = "République d'Afrique du Sud"
    strValue2 = "Republic of South Africa"
    iComparisonValue = StrComp(strValue1, strValue2, vbTextCompare)
    
    Response.Write "Comparing """ & strValue1 & """ with """ & _
           strValue2 & """ produces " & CStr(iComparisonValue)
End Sub
 
 
   
 

Home Copyright © 2008-2009 FunctionX