Using Visual Basic 6

Previous chapterNext chapterContents


- 12 -
Working with Strings and Typecasting


Manipulating Strings

The first task when working with strings is to be able to locate parts of a string and then rearrange them as required.


Visual Basic 6's string functions

Visual Basic 6 comes with a lot of new string functions, many of them vast functional enhancements to the native language. Seasoned VB programmers can now replace entire custom functions in their programs with a single line of code. Because of VB6's numerous new string functions, expect to refer to this chapter several times before you uncover all that can be accomplished with these new functions.


Reversing the Order of Characters in Strings

Visual Basic's new StrReverse() function enables you to completely reverse the order of a string. Its syntax is as follows:

strResult = StrReverse(strMyString)

In this syntax,

The TextBoxes shown in Figure 12.1 were initialized during the form's load event. Notice that line 3 of the following code is an empty string of length zero. It's important to distinguish this from a null string. Most databases, such as Microsoft Access and SQL Server, allow fields to be null or undefined until they're initialized. These null values will cause problems for the string functions.

01 Private Sub Form_Load()
02 txtMyString.Text = "It's raining cats and dogs."
03 txtResult.Text = ""
04 End Sub

Visual Basic defaults all internal variables to valid values--numeric variables default to zero, and strings default to empty. The problem happens when you take a null data field from a database and assign it to an internal variable or when you perform a string function on the null data field.

The sample program in Figure 12.1 uses two ways of reversing a string. Listing 12.1 shows the code required for Visual Basic 5. In this version, a loop was required to step through each character in the string and then build the new string in reverse order. The code in Listing 12.2 delivers the same result with the new StrReverse() function, with no loops and only one simple command.

FIGURE 12.1 The string is reversed by either the old or the new string-reversing subroutines.

LISTING 12.1  12LIST01.TXT--A VB5 For...Loop That Reverses a String by Using
the Len() Function

01 Private Sub OldVersion_Click()
02 Dim intLength As Integer `Length of the string
03 Dim intCntr As Integer `Loop counter
04
05 `Initialize the txtResult.Text string and then
06 ` determine the length of txtMyString.Text
07 intLength = Len(txtMyString.Text)
08 txtResult.Text = ""
09
10 `Loop through the first string one character at a time.
11 `Concatenate each character to the beginning.
12 For intCntr = 1 To intLength
13 txtResult.Text = Mid(txtMyString.Text, intCntr, 1) _
& txtResult.Text
14 Next intCntr
15 Refresh
16
17 End Sub


Download this chapter's code

You can find all the code for the examples in this chapter on the Web at http://www.mcp. com/info. At the prompt, enter 078971633x (for the book's ISBN) and then click Search to go to the Book Info page for Using Visual Basic 6.


LISTING 12.2  12LIST02.TXT--Using the New StrReverse() Function

01 Private Sub NewVersion_Click()
02 `This new function works on strings.
03
04 txtResult.Text = StrReverse(txtMyString.Text)
05 Refresh
06
07 End Sub

Listing 12.2's seven code lines are more for contrast than function. Only lines 4 and 5 perform any actions. Notice, however, that because a simple assignment statement could be used, the value of txtResult.Text didn't have to be initialized, further reducing the lines of code required.

Replacing Characters Within Strings

The next new function to introduce is Replace(), which can find and then replace or remove the found string within the target string. Find operations also can either consider or ignore capitalization. If you've ever used the replace feature in a word processing program, you have a good understanding of how this function works.

The syntax for the Replace() function is as follows:

strResult = Replace(strMyString, strFind, strRplWith, _
                    intStart, intCnt, intCompare)


Replace() can return a partial string

A feature of the Replace() function is that it returns only the portion of the string to which the function was directed to work on. When you specify the optional parameter intStart with a value greater than 1, the return string won't contain the characters before the intStart position.


In this syntax,

The intCompare argument has several settings (see Table 12.1). The first option enables the function to be driven by the global compare option, which can be set in the general declaration section of the program. This makes changing the case sensitivity for all Replace() functions in a program as simple as changing one line of code.

TABLE 12.1  Options for the intCompare Argument

Constant Value Description
vbUseCompareOption -1 Performs a comparison as set in the Option Compare statement
vbBinaryCompare 0 Performs a case-sensitive comparison
vbTextCompare 1 Performs a comparison that is not case sensitive

The program in Figure 12.2 uses the string contained in the first TextBox as the target of a search-and-replace operation.

FIGURE 12.2 The word cats is replaced with the word horses in both locations in the string.

As with the example for reversing a string, the sample program in Figure 12.2 initializes the TextBox Text properties when the form is loaded. In the following code, lines 3 and 4 show the values of the strFind and strRplWith arguments, respectively.

01 Private Sub Form_Load()
02 txtMyString.Text = "It's raining cats and dogs" _
               & "and dogs and cats"
03 txtFind.Text = "cats"
04 txtRplWith.Text = "horses"
05 End Sub

When the click event is fired, the assignment statement takes the return value from the Replace() function and assigns it to the Text property of TextBox1. Line 3 in the following code uses the continuation symbol (_) to allow the statement to extend to the next line.

01 Private Sub cmdReplace_Click()
02 `The Replace function works on strings.
03 txtMyString.Text = Replace(txtMyString.Text, _
        txtFind.Text, txtRplWith.Text)
04 Refresh
05 End Sub

When the TextBoxes are updated (see Figure 12.3) with horses as the strFind value and "" (the zero-length string) as the strRplWith value, the function will replace the found string with nothing. This is how you can use the function to remove only the found values, but notice again that both locations in the string were changed.

FIGURE 12.3 The Replace() function can also remove characters.

The power of Replace also offers the opportunity to create errors. Table 12.2 lists six conditions that, when you're writing programs, you need to understand and check for. Each condition identifies a return value when the function is given a certain input to work with.


Replace() won't always work

It's important to be able to process the return values of the Replace() function when an error has occurred. This function can err in several ways that are important to capture in your program.


TABLE 12.2  Return Values from Errors in the Replace() Function

When... Replace() Returns...
strMyString is zero length A zero-length string of ""
strMyString is null An error
strFind is zero length A copy of strMyString
strRplWith is zero length A copy of strMyString with all occurrences of strFind removed
intStart > Len(strMyString) A zero-length string of ""
intCnt is 0 A copy of strMyString

When the value of strFind or strRplWith is a zero-length string, an unwanted result might occur that you can trap with a simple If...Then statement around the function. The following code and Figure 12.4 show how the function on line 3 of the preceding example could be changed to check for this condition. This would be important if you wanted to prevent any replacement of characters when the strFind or strRplWith string is empty.

01 Private Sub cmdReplace_Click()
02 `Test for Empty String; then Replace the strings.
03 If txtFind.Text = "" Or txtRplWith = "" Then
04      MsgBox "You Found the Error", vbExclamation, _
         " Empty String data error"
05 Else
06      txtMyString.Text = Replace(txtMyString.Text, _
         txtFind.Text, txtRplWith.Text)
07 End If
08 Refresh
09 End Sub

There are many other techniques for finding and processing errors. Chapter 21, "Debugging Your Applications," covers these more extensively.

FIGURE 12.4 The Replace() function parameters should be checked for unwanted values.

Concatenating Strings

Concatenating one string to another means combining both strings. In Visual Basic, you concatenate two strings by using the & operator. In Listing 12.3, the value of strResult will be blueberry.


More efficient code

This example helps you understand the role of variables and literals. The same result could be achieved in one line: cmdBerry.Caption = "blue" & "berry".


LISTING 12.3  12LIST03.TXT--Simple Concatenation of Two Strings

01 Private Sub cmdBerry_Click()
02 Dim strMine As String
03 Dim strYours As String
04 Dim strResult As String
05
06 strMine = "blue"
07 strYours = "berry"
08 strResult = strMine & strYours
09
10 cmdBerry.Caption = strResult
11 End Sub

You can also concatenate more than two strings together with the & operator. For example, you might want to add a space character between a first name and last name, as shown in Listing 12.4. Figure 12.5 shows Listing 12.4's code in action.

LISTING 12.4  12LIST04.TXT--Concatenating More Than Two Strings

01 Private Sub cmdFullName_Click()
02 Dim strFirst As String
03 Dim strLast As String
04 Dim strFull As String
05
06 `Get the first name for the textbox
07 strFirst = txtFirst.Text
08
09 `Get the last name from another textbox
10 strLast = txtSecond.Text
11
12 `Concatenate the first and last name, putting
13 `a space character between them.
14 strFull = strFirst & " " & strLast
15
16 `Display the Full Name
17 lblResult.Caption = strFull
18
19 End Sub

FIGURE 12.5 Using the + character to concatenate strings is a holdover from earlier versions of Visual Basic and can produce unwanted results if your string variables have numbers in them. See the sample program later in the section "Controlling Data Types with Typecasting."

Determining a String's Length with Len()

You use the Visual Basic Len() function to determine how many characters are in a given string. You'll use this function often, particularly with the other string-manipulation functions.

The syntax of the Len() function is as follows:

intResult = Len(strMyString)

In this syntax,

Listing 12.5 shows how to use the Len() function. Figure 12.6 shows the result of Listing 12.5 in action.

LISTING 12.5  12LIST05.TXT--Using the Len() Function

01 Private Sub cmdFindLen_Click()
02 Dim strFind As String
03 Dim intLen As Integer
04
05 `Assign a string to find to the local variable
06 strFind = txtFirst.Text
07
08 `Find the length of the string
09 intLen = Len(strFind)
10
11 `Report the results
12 lblResult.Caption = CStr(intLen)
13 End Sub

FIGURE 12.6 You can also use Len() to find the size (in bytes) of a nonstring variable.

Truncating Strings with Left() and Right()

You use the Left() and Right() functions to truncate strings. Informally, to truncate a string means to cut off part of it to make the string smaller. The Left() function returns a certain number of characters from the left side of a given string to a buffer string. (A buffer string is a holding string.)

The Right() function is similar to the Left() function, but rather than return characters from the left side of a string, Right() returns a given number of characters from the right side of a string.

The following is the syntax for the Left() and Right() functions:

strResult = Left(MyString, lNumToReturn)
strResult = Right(MyString, lNumToReturn)

In this syntax,

Listing 12.6 shows how to use the Left() and Right() functions to truncate a given amount of characters from a string. Figure 12.7 shows the result of this code.

LISTING 12.6  12LIST06.TXT--Using the Left() and Right() Functions

01 Private Sub cmdLeft_Click()
02 Dim intChrCnt As Integer `Number of characters
03 Dim strBuffer As String `String buffer
04 Dim strMyString As String `String to truncate
05
06 `Convert the numeral for the number of
07 `characters to truncate to a number
08 intChrCnt = CInt(txtSecond.Text)
09
10 `Get the string to truncate
11 strMyString = txtFirst.Text
12
13 `Truncate the string by using the Left() function
14 strBuffer = Left(strMyString, intChrCnt)
15
16 `Display the results
17 lblResult.Caption = strBuffer
18 End Sub
19
20 Private Sub cmdRight_Click()
21 Dim intChrCnt `Number of characters to return
22 Dim strBuffer `string buffer
23 Dim strMyString As String `string to truncate
24
25 `Convert the numeral for the number of
26 `characters to truncate to a number
27 intChrCnt = CInt(txtSecond.Text)
28
29 `Get the string to truncate
30 strMyString = txtFirst.Text
31
32 `Truncate the string by using the Right() function
33 strBuffer = Right(strMyString, intChrCnt)
34
35 `Display the results
36 lblResult.Caption = strBuffer
37 End Sub

FIGURE 12.7 Left() returns a given number of characters from the left side of a string; Right() returns a given number of characters from the right side.

FIGURE 12.7b

Using Mid() to Return Characters from Inside a String

The Mid() function returns a string of a given number of characters from a specified location in another string. For example, if you want to return the string "Allen" from the string "Edgar Allen Poe", you use the Mid() function.

The syntax for the Mid() function is as follows:

strResult = Mid(MyString, lngStart[, lngSize])

In this syntax,

MyString = "Edgar Allen Poe",
strResult = Mid(MyString, 5, 5)
MyString = "Edgar Allen Poe",
strResult = Mid(MyString, 5)

Listing 12.7 shows you how to use the Mid() function to extract a substring from a string.


The space character occupies a character position

Notice in this example that the space clearly occupies position 6 and Allen doesn't start until position 7.


LISTING 12.7  12LIST07.TXT--Using the Mid() Function

01 Private Sub cmdSimpleMid_Click()
02 Dim strBuffer As String `String Buffer
03 Dim strMyString As String `The string on which
04 `to perform the Mid() function
05
06 Dim lngStart As Long `The starting position
07 `of the Mid()function
08
09 Dim lngSize As Long `Size of the string to return
10
11 `Assign the text in the first textbox to the
12 `MyString variable
13 strMyString = txtFirst.Text
14
15 `Convert the numeral in the second textbox to a
16 `LONG and assign it to the starting position
17 `variable.
18 lngStart = CLng(txtSecond.Text)
19
20 `Convert the numeral in the third textbox to a
21 `LONG and assign it to the return size variable.
22 lngSize = CLng(txtThird.Text)
23
24 `Run the Mid() function and assign the result to
25 `the buffer variable.
26 strBuffer = Mid(strMyString, lngStart, lngSize)
27
28 `Display the result in a textbox.
29 txtHold.Text = strBuffer
30 End Sub

The Mid() function is powerful. It takes some practice to get accustomed to using it. Remember the following helpful hints:

Using InStr() to Search for Characters Within a String

You use the InStr() function to determine whether a character or string exists within another string. If it does, the function returns a Long that reflects the position of the located string. For example, if you want to know whether a decimal character is in a string, 123.345, you use the Instr() function. The syntax for the InStr() function is

lngResult = InStr([intStart, ]strMyString, strFind[, intCompare])

In this syntax,

Listing 12.8 shows you how to use the InStr() function; Figure 12.8 shows the code in action.

LISTING 12.8  12LIST08.TXT--Using the InStr() Function

01 Private Sub cmdInStr_Click()
02 Dim lngResult As Long
03 Dim strMyString As String
04 Dim strFind As String
05 Dim lngStart As Long
06
07 `Assign the value for the string in which you are
08 `going to look for your character or string.
09 strMyString = txtFirst.Text
10
11 `Get the string you want to look for from the
12 `TextBox
13 strFind = txtSecond.Text
14
15 `If the TextBox is not empty, get the starting
16 `position for the search
17 If txtThird.Text <> "" Then
18 lngStart = CLng(txtThird.Text)
19 Else
20 `If it is empty, set the starting position to
21 `the first character
22 lngStart = 1
23 End If
24 lngResult = InStr(lngStart, strMyString, strFind)
25
26 `Display the answer
27 txtHold.Text = CStr(lngResult)
28 End Sub

FIGURE 12.8 The InStr() function reports the position of the first occurrence of a given character or string. To search for other occurrences, you must set the function's lngStart argument.

Using Strings and Arrays of Strings

One of the more time-consuming parts of working with strings and arrays of strings is the extensive programming required to manipulate and prepare lists. Many extensive programs have been written to handle the tasks. The following three new functions provide easy control over any long string of words and provide for the creation of arrays from those lists.

The sample program used in this section reads a long string of modem filenames from a text file and then demonstrates the use of each new function. Listing 12.9 details the declarations and the first command button that loads the list of filenames into a public string variable; Figure 12.9 shows the initial screen.

LISTING 12.9  12LIST09.TXT--Declarations and Load Statements for the
Filter.vbp Program

01 Public strModems As String
02 Public varFull As Variant
03 Public varFilter As Variant
04
05 Public Sub Form_Load()
06 `When the form is loaded, display the current path
07 ` and the filename. Clear the two ListBoxes
08 txtDir.Text = CurDir & "\MODEM.TXT"
09 lstFull.Clear
10 lstFilter.Clear
11 End Sub
12
13 Private Sub cmdLoad_Click()
14 Dim intFile As Integer
15 ` Find the next free File handle
16 intFile = FreeFile
17 ` Open the modem file for input and then read
18 ` the first and only row into Public strModem
19 Open CurDir & "\MODEM.TXT" For Input As #intFile
20 Input #intFile, strModems
21 Close #intFile
22 `Display the String in the TextBox
23 txtList.Text = strModems
24 End Sub

FIGURE 12.9 The Filter.vbp program starts with the Load File command, which reads a text file for a list of modem filenames.

Line 23 in Listing 12.9 displays the contents of strModems in the second TextBox on the form. This is the data used throughout the sample program and is a public string variable. The program also uses two variant-type variables to hold the array of strings for the Split() and Filter() examples.

Splitting a String into an Array of Strings with Split()

Visual Basic's new Split() function takes a list of words or numeric values stored in a string and breaks them into individual elements of an array of strings. In past versions of Visual Basic, this function would require several complex programming steps to walk through the string and build the array. The key to using this function is knowing how the string to be separated is constructed. In the case of a sentence, a space acts as the delimiter. A row from a data file can contain numbers and words separated by a comma. Either option will work with this function.


Delimiters can be more than one character

Delimiters aren't limited to a single character, such as a space or a comma. Any valid string of characters can be used. The important feature to remember is that the delimiter isn't returned with the substring. If the only distinguishing separator is an important part of the word or data field, you can add the delimiter back after creating the array.


The syntax for Split() is as follows:

varResult = Split(strList, strDelimiter, intElemCnt, intCompare)

In this syntax,

Constant Value Description
vbUseCompareOption -1 Performs a comparison by using the setting of the Option Compare statement
vbBinaryCompare 0 Performs a binary comparison
vbTextCompare 1 Performs a textual comparison
vbDatabaseCompare 2 Performs a comparison based on information in your database (for Microsoft Access only)

Listing 12.10 shows the Split() function being used to turn a long string into a array of strings. Lines 21-23 detail the For...Loop that's used to add the elements of the array of strings to the ListBox. The lstFull ListBox contains all the values in the strModems string unless the delimited CheckBox is selected. Lines 7-14 check this condition, and if checked, the list is built with only six values from the original.

LISTING 12.10  12LIST10.TXT--String Splitting with an Optional Delimiter

01 Private Sub cmdList_Click()
02 Dim intRecCnt As Integer
03 Dim intCntr As Integer
04
05 `Check if the String is to be split with the default
06 `delimiter.
07 If chkDelimit.Value Then
08 `If checked, use the value in the txtFilter
09 `TextBox and limit the number of elements to 6
10 varFull = Split(strModems, txtFilter.Text, 6)
11 Else
12 `If not checked, use the default values for Split()
13 varFull = Split(strModems)
14 End If
15
16 `Determine the number of elements in the array
17 intRecCnt = UBound(varFull)
18
19 lstFull.Clear
20 `Add Elements to ListBox for each element in array
21 For intCntr = 0 To intRecCnt _
22 lstFull.AddItem varFull(intCntr)
23 Next intCntr
24
25 Refresh
26 End Sub

Creating a Sublist from an Array of Strings with Filter()

The Filter() function builds on the power of the Split() function. When you have your list in an array of strings, the Filter() function lets you create a new list that's a filtered version of your first list. This function, like the Split() function, returns an array of strings.

The syntax for Filter() follows:

varResult = Filter(varlist, strFind, bolInclude, intCompare)

In this syntax,

If no matches of strFind are found within the string array varList, the function returns an empty array. If varList is null or isn't a one-dimensional array, an error is returned. Listing 12.11 shows the code used to select from an array with the Filter() function.

LISTING 12.11  12LIST11.TXT--Using Filter() to Select from an Array

01 Private Sub CmdFilter_Click()
02 Dim intRecCnt As Integer
03 Dim intCntr As Integer
04
05 `Create the Filtered array from the Full array
06 varFilter = Filter(varFull, txtFilter.Text)
07
08 `Determine the number of elements in the array
09 intRecCnt = UBound(varFilter)
10
11 lstFilter.Clear
12 `Add Elements to ListBox for each element in the array
13 For intCntr = 0 To intRecCnt _
14 lstFilter.AddItem varFilter(intCntr)
15 Next intCntr
16
17 Refresh
18 End Sub

Combining an Array of Strings with Join()

The new Join() function is the counterpart to the Split() function. This function combines all the elements in an array of strings into one single string. The optional delimiter enables the delineation of the separate elements on the string, which allows for enhanced processing in the future.

The syntax for Join() is as follows:

strResult = Join(varList, strDelimiter)

In this syntax,

Line 9, or line 12, performs the join in Listing 12.12. If the delimited CheckBox has been marked, the join will use the value in the txtFilter.Text property (line 9) for the delimiter. The sample program lets you try various combinations of characters for delimiters. The resulting new string is placed in the txtListBox, which is the highlighted ListBox in Figure 12.10. Notice that in this example, two characters (**) are used as a delimiter.

LISTING 12.12  12LIST12.TXT--Putting Together an Array of Strings

01 Private Sub CmdJoin_Click()
02 Dim intRecCnt As Integer
03 Dim intCntr As Integer
04
05 `Check if the Join will use the default delimiter
06 If chkDelimit.Value Then
07 `If checked, use the value in the txtFilter
08 `TextBox to separate the Sub-strings
09 txtList.Text = Join(varFilter, txtFilter.Text)
10 Else
11 `If not checked, use the default values for Join()
12 txtList.Text = Join(varFilter)
13 End If
14 Refresh
15 End Sub

FIGURE 12.10 You can join an array of strings by using any character as the delimiter.

Changing a String's Case with UCase() and LCase()

The UCase() and LCase() functions affect the case of a given string or character. The UCase() function returns a string in which all the characters are set to uppercase, whereas the LCase() function returns a string in which all the characters are set to lowercase. The following is the syntax for the UCase() and LCase() functions:

strResult = UCase(strMyString)
strResult = LCase(strMyString)

In this syntax,

Listing 12.13 shows you how to use UCase() and LCase() to set a given string to uppercase and lowercase; Figure 12.11 shows the code example in action.

LISTING 12.13  12LIST13.TXT--Using the UCase() and LCase() Functions

01 Private Sub cmdUpper_Click()
02 Dim strBuffer As String `string buffer
03 `Assign the characters in the first textbox
04 `to the buffer variable
05 strBuffer = txtFirst.Text
06
07 `Set all the characters in the buffer to
08 `uppercase and display the result
09 lblResult.Caption = UCase(strBuffer)
10 End Sub
11
12 Private Sub cmdLower_Click()
13 Dim strBuffer As String `String buffer
14 `Assign the characters in the first textbox
15 `to the buffer variable
16 strBuffer = txtFirst.Text
17
18 `Set all the characters in the buffer to
19 `lowercase and display the result
20 lblResult.Caption = LCase(strBuffer)
21 End Sub

FIGURE 12.11 UCase() and LCase() are closely related functions.

Using String-Parsing Functions

Now that you've seen how to do basic string manipulation with the Len(), Left(), Right(), Mid(), and InStr() functions, you're going to put what you've learned to more detailed use.

String parsing--the activity of stripping and manipulating strings--is a common activity among programmers. One of the most common parsing requirements that programmers encounter is retrieving the first-name string and the last-name string from a full-name string. You'll now study a set of user-defined functions that do this: GetFirstName(), which returns the first name from the full name, and GetLastName(), which returns the last name from the full name. Both functions take one argument: a string indicating the full name. These functions are designed around a central conceptual principle (and assumption) that within a full-name string, the first name is separated from the last name by a space character and that if you know the location of the space character in the full-name string, you can strip out the first-name characters and the last-name characters.

Figure 12.12 illustrates the logic of determining the first-name and last-name strings from a full-name string. In Listing 12.14, you can see the code for the functions GetFirstName() and GetLastName().

FIGURE 12.12 The most important thing that you need to know in order to parse names from a string is the position of the space characters.

LISTING 12.14  12LIST14.TXT--Using GetFirstName() and GetLastName() to Parse
Strings

01 Public Function GetFirstName(strFullName As String) _
As String
...
20 Dim lSpacePos As Long `Position of space char
21 `in a string
22 Dim strSpaceChar As String `Space character
23 Dim strFirstName As String `Buffer for First Name
24 Dim lngResult As Long `Result variable
25 Dim lngLeftLen As Long `Number of characters
26 `Name
27
28 `Use the IsValid function to make sure that the
29 `Full Name string has only one space character in it
30 If IsValid(strFullName) = False Then
31 `If it doesn't, return the error string
32 GetFirstName = "Error"
33 `And exit the function
34 Exit Function
35 End If
36
37 `Define space character
38 strSpaceChar = " "
39
40 `Find the position of the space character within the
41 `full-name string.
42 lngResult = InStr(1, strFullName, strSpaceChar)
43
44 `The position of the space character is also
45 `the length to extract for the left side (First Name)
46 lngLeftLen = lngResult
47
48 `Extract the First Name and assign it to the
49 `First Name variable
50 strFirstName = Left(strFullName, lngLeftLen)
51
52 `Return the value of the first name
53 GetFirstName = strFirstName
54 End Function
55
56 Public Function GetLastName(strFullName As String) _
As String
...
75 Dim lSpacePos As Long `Position of space
76 `character in a string
77 Dim strSpaceChar As String `Space character
78 Dim strLastName As String `Buffer string
79 Dim lngResult As Long `Result variable
80 Dim lRightLen As Long `Num of chars in Last Name
81
82 `Use the IsValid function to make sure that the
83 `Full Name string has only one space character.
84 If IsValid(strFullName) = False Then
85 `If it doesn't, return the error string
86 GetLastName = "Error"
87 `And exit the function
88 Exit Function
89 End If
90
91 `Define space character
92 strSpaceChar = " "
93
94 `Find the position of the space character
95 lngResult = InStr(1, strFullName, strSpaceChar)
96
97 `Define the number of characters to extract from
98 `the right of the space character, (Last Name).
99 `If you subtract the position of the space character
100 `for the total number of characters in the Full Name
101 `string, this will yield the number of characters to
102 `extract from the right side of the Full Name string.
103 `This technique avoids including the space character
104 `itself by accident.
105 lRightLen = Len(strFullName) - lngResult
106
107 `Extract the right side of the Full Name string and
108 `assign it to the Last Name Buffer
109 strLastName = Right(strFullName, lRightLen)
110
111 `Return the value of the Last Name string out of the
112 `function.
113 GetLastName = strLastName
114 End Function

You might have a full name that contains a middle name or middle initial or have a last name made up of two strings, such as Von Beethoven. In this case, the function wouldn't be valid. You build a validation function, IsValid(), to determine whether the string can be parsed into a first name and last name. Figure 12.13 illustrates the logic for the user-defined function IsValid(), and Listing 12.15 shows the code for the function.

FIGURE 12.13 Loops are an excellent way to traverse a string, provided you know the string's length.

LISTING 12.15  12LIST15.TXT--Testing to Verify Only One Space Character Per
String

01 Public Function IsValid(strFullName) As Boolean
02 `****************************************
03 `Sub/Function: IsValid
04 `
05 `Arguments: strFullName A string representing a full
06 ` name to validate
07 `
08 `Return: True, if the string has only 1
09 ` character
10 `
11 `Remarks: This function is used to
12 ` determine if more than one
13 ` space character exists in a string.
14 `
15 `Programmer: Bob Reselman
16 `
17 `Copyright 1998, Macmillan Publishing
18 `****************************************
19
20 Dim intSpaces As Integer `Hold the count of the
21 `number ofspaces in a string
22 Dim intChars As Integer `Number of characters
23 Dim intCntr As Integer `Counter variable
24 Dim strSpace As String `The space character
25 Dim strPresent As String `A buffer to hold one
26 `character to examine
27 `Define the space character
28 strSpace = " "
29
30 `Find out how many characters are in the full name
31 intChars = Len(strFullName)
32
33 `Loop through the entire string, strFullName
34 For intCntr = 1 To intChars
35 `Look at each character one at a time
36 strPresent = Mid$(strFullName, intCntr, 1)
37 `If the character that you are inspecting is a
38 `space....
39 If strPresent = strSpace Then
40 `...Increment the space counter variable by 1
41 intSpaces = intSpaces + 1
42 End If
43 Next intCntr
44
45 `If there is only one space in the Full Name string...
46 If intSpaces = 1 Then
47 `...return True
48 IsValid = True
49 Else
50 `If not, return False
51 IsValid = False
52 End If
53 End Function

If you want to see this code in action, go to the project AdvncStr.VBP, which you can download from http:// www.mcp.com/info. When you run the code, you'll see buttons for the GetFirstName() and GetLastName() functions, as well as one to test the IsValid() function. Enter a full name in the txtHold TextBox and then click the buttons to see the results.

Controlling Data Types with Typecasting

When you typecast a variable, you transform its value from one type to another. As you read earlier, Visual Basic is so highly automated that it hides many mundane chores of typecasting from you. Consider the following code:

Private Sub cmdAutoType_Click()
    txtFirst.Text = 5
End Sub

The data type that the Text property expects is a String, but it's being assigned an Integer. However, it works! Visual Basic automatically takes the Integer 5 and converts it to a String type. You would have to do a lot to get this code to work in a more type-safe language such as C++.

Now consider the following code (Figure 12.14 shows this code in action):

Private Sub cmdError_Click()
    lblResult.Caption = txtFirst.Text + txtSecond.Text
End Sub

FIGURE 12.14 Concatenating string variables yields a different result than adding integers.

Notice that Visual Basic's automated nature has now broken down. If you type 5 and 2 in the TextBoxes, the result is the string 52, not the integer 7. VB will convert 5 to an integer only if you try to add it to a value or variable of type Integer; the + operator works just like & for strings.

Therefore, to ensure that integer addition does indeed happen as you plan it to, you must convert at least one TextBox Text value to an integer by using the CInt() function. For example, in the following code snippet, if txtFirst.Text and txtSecond.Text hold numeric strings, the value of lblResult's Caption property will be the result of integer addition:

lblResult.Caption = CInt(txtFirst.Text) + txtSecond.Text

Letting Visual Basic do most of the work with regard to data types might serve you well, but as you can see from the preceding example, gaining control of data types and typecasting is a skill that you need to develop over the long term.

Changing Data Types with the Conversion Functions

Throughout this book you've seen the functions CStr() and CInt() used liberally with no real explanation. These functions are conversion functions. A conversion function transforms a value from one data type to another. In Visual Basic, you use the conversion functions to typecast.

Because experienced Visual Basic programmers try to impose as much type safety on their code as they can, among seasoned programmers it's not unusual to find the value of an object's property typecast before it's applied to a variable. Of course, before you try to convert a value from one type to another, make sure that the value is appropriate to the type. For example, the following would be erroneous:

strMyString = "Batman"
intCounter - CInt("Batman")
intCounter = strMyString$

Table 12.3 shows the type conversion functions and provides a discussion and example of each function.


Testing for proper data in your programs

Ensuring that data type conversion is possible is where validation functions such as IsNumeric(), IsValue(), and IsDate() come in handy. For a detailed discussion of these functions, read Visual Basic's online help.


TABLE 12.3  Type Conversion Functions

Function Comments Example
CBool() Converts a value to a Boolean CBool(-1)
CByte() Converts values between 0 and 255 to a Byte Cbyte(254)
CCur() Converts a value to Currency CCur("$23.98")
CDate() Converts a date expression to a Date data type CDate("July 4, 1776")
CDbl() Converts a value to a Double CDbl(MyInt%)
CDec() Used only with variants N/A
CInt() Converts a value to an Integer CInt("4")
CLng() Converts a value to a Long CLng(Form1.hWnd)
CSng() Converts a value to a Single CSng("23.1")
CVar() Converts a value to a Variant CVar(Text1.Text)
CStr() Converts a value to a String CStr(MyInt%)

Validating Data with IsNumeric()

As your programs rely more on valid user input, you must address the issue of users inputting text strings when you need them to enter numeric strings. Visual Basic has a built-in function that will help: IsNumeric(). IsNumeric() checks a string to see whether it "looks" like a number. If a string looks like a number, IsNumeric() returns True; otherwise, it returns False. The syntax for IsNumeric() is as follows:

bResult = IsNumeric(MyString)

In this syntax,

Listing 12.16 shows code that uses IsNumeric() to check whether user input can be assigned to variables of type Integer.

LISTING 12.16  12LIST16.TXT--Using IsNumeric() to Validate User Input

01 Private Sub cmdIsNumeric_Click()
02 Dim intAnswer As Integer
03 Dim intX As Integer
04 Dim intY As Integer
05
06 If IsNumeric(txtFirst.Text) = True Then
07 intX = CInt(txtFirst.Text)
08 Else
09 MsgBox "Type Error", vbCritical
10 Exit Sub
11 End If
12
13 If IsNumeric(txtSecond.Text) = True Then
14 intY = CInt(txtSecond.Text)
15 Else
16 MsgBox "Type Error", vbCritical
17 Exit Sub
18 End If
19
20 intAnswer = intX + intY
21
22 lblResult.Caption = CStr(intAnswer)
23 End Sub

Table 12.4 lists all the Visual Basic validation functions.

TABLE 12.4  Visual Basic's Validation Functions

Function Test Condition
IsArray() Returns True if the variable is an array
IsDate() Returns True if the expression is a valid date
IsEmpty() Returns True if the variable hasn't been initialized or has been set to empty
IsError() Returns True if a numeric expression represents an error
IsMissing() Returns True if no value has been passed to a function
IsNull() Returns True if the expression is null or has been set to null
IsNumeric() Returns True if the entire expression is a number
IsObject() Returns True if the expression is an object


Previous chapterNext chapterContents

© Copyright, Macmillan Computer Publishing. All rights reserved.