Visual Basic 2008 Programming: Business Applications with a Design Perspective
Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9
Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14 Appendix A Appendix B Appendix C Home
Loading
Last change: February 13 2016 18:48:19.

 Chapter in PDF

Table of Contents

Chapter 4: Data, Operations, and Built-In Functions
Last change: February 13 2016 18:47:36.
<<PreviousNext>>

String Operations and Built-In Functions

You cannot perform computations on string data; however, you can perform concatenation on strings. The concatenation operation joins two separate strings. You can use either + or & as the symbol for the concatenation operation. Here are two examples of concatenations:

EmployeeName = “John ” + “Smith” EmployeeName = txtFirstName.Text & “ “ &  txtLastName.Text

The first line will result in the string “John Smith” being assigned to the variable EmployeeName. In the second line, the content of the text box named txtFirstName is first concatenated with a blank space. The result is then concatenated with the content of the text box named txtLastName. Finally, this result is assigned to the variable EmployeeName. If txtFirstName contains the string “John” and txtLastName contains the string “Smith,” EmployeeName will have the string “John Smith” as the result.

The Ambiguous + Operator

Both + and & symbols can be used for the concatenation operation; however, the + operator can be ambiguous. This is particularly true when one of the operands involved is a string, and the other is a number. Consider these lines:

Dim Text As String Text = “123” + “123” Text = “123” + 123 Text = “ABC” + 123

The first line will result in Text containing the string “123123” as expected. The second line, however, will result in text containing a string value of “246.” Because 123 is a number, VB considers + an addition operation, instead of concatenation; therefore, “123” is first converted to a number 123. The two numbers are then added together. The resulting value is converted to a string before it is assigned to the variable Text.
The third line will cause a run time Invalid cast exception. Again, VB treats the expression as a numeric addition first. When it is unable to successfully convert the string “ABC” to a number, it issues an error message. As you can see, using the + operator for string concatenation can cause confusing results. Avoid using it by all means.
If you mean to have string concatenations for the previous examples, the following lines will produce the correct results:

Dim Text as String Text = “123” & “123” Text = “123” & 123 Text = “ABC” & 123

Because VB knows the & operator is only used for string concatenation, it will first convert 123 into a string “123” in the last two lines. The first two lines will result in a string of “123123,” and the third line results in “ABC123.”

On Strict Conversion Again

If you observe strict data type conversion, you would not have coded some of the above lines as they were. In each of those lines that involved mixed types of data, you would convert one of the operands into the type of the other operand to ensure that the meaning is clear. For example, line 2 in the above two cases can be coded as follows (imagine the value 123 is actually represented by a numeric variable):

Text = “123” + CStr(123) Text = “123” & CStr(123)

No ambiguity will result as to what kind of operation you expect to perform. Observing strict data type conversion is a good practice to follow. Set Option Strict On in your project to make the compiler force you to observe strict conversion rules.

Try This
Type the following code in the code window of a new project with Option Strict Off. Run the project, click the form, and observe the results; then replace the + symbol with the &” symbol. Repeat the test, and you should be able to get a good feel about how VB treats the two symbols.
Private Sub Form1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Click Dim Text123 As String Dim TextABC As String Text123 = "123" + 123 MsgBox("Text123 is " & Text123) TextABC = "ABC" & 123 MsgBox("TextABC is " & TextABC) End Sub
Tip
Because the & symbol is also used as a type suffix, you must be sure that there is a space between this symbol and the variable before it to avoid a syntax error. For example, the following expression will cause an error.
FirstName& “ “ & LastName  
But the following expression (notice the space before &) will produce no error.
FirstName & “ “ & LastName

Built-In String Functions

In addition to the concatenation operation, many built-in string functions can be used to manipulate string data. The following table lists selected functions.

Function Use
Asc(char) Returns the ASCII key code value of a character (one byte); for example, Asc(”A”) returns 65
AscW(char) Returns the key code value of a character (two bytes); for example, AscW(“A”C) returns 65.
Chr(n) Returns a character with an ASCII value n; for example, Chr(65) returns “A”.
ChrW(n) Returns a character in Unicode with a value n; for example, ChrW(65) returns “A”C.
Val(S) Converts the string S to a numeric value; for example, Val(”-23.5”) returns –23.5.
Str(n) Converts a number n into a string; for example, Str(-23.5) returns “–23.5”.
StrReverse(S) Returns a string of the mirror image of the string S; for example, StrReverse(''AB'') returns “BA”.
LCase(S) Returns the lowercase of the string S; for example, LCase(”AbC”) returns “abc”.
UCase(S) Returns the uppercase of the string S; for example, UCase(''AbC'') returns “ABC”.
Space(n) Generates a string with n blank spaces; for example, Space(1) returns “ ”.
StrDup(R, C) Returns a string of R number of repeated characters, C. For example, StrDup(3,”A”) returns “AAA”.
Left(S, n) Returns a string with the first n characters of the string S; for example, Left(”My Name”, 2) returns “My”.
Right(S, n) Returns a string with the last n characters of the string S; for example, Right(''My Name'', 4) returns “Name”.
Mid(S, b, [n]) Returns a string of n characters that starts at the bth position in S; for example, Mid(''My Name'', 2, 3) returns “y N”.
InStr([p],S, c) Returns the position in S at which the content matches the string c. The comparison will start at position p. If p is omitted, it will start at position 1; for example, InStr(”My Name”, ”y”) returns 2.
InStrRev(S,c,[p]) Returns the position in S at which the content matches the string c. The comparison goes backward from position p. If p is omitted, it will start from the end; for example, InStrRev(”02-02-43”, ”-“) returns 6.
Len(S) Returns the length of the string; for example, Len(''My Name'') returns a value 7.
LTrim(S) Returns a string with all leading blank spaces trimmed off; for example, LTrim(” My “) returns “My ”.
RTrim(S) Returns a string with all trailing blank spaces trimmed off; for example, RTrim(” My “) returns ” My”.
Trim(S) Returns a string with all the leading and trailing spaces trimmed off; for example, Trim('' My '') returns “My”.
Replace(S, a, b) Replaces all a’s in S with b; for example, Replace(“Jeff”, “f”, “s”) returns “Jess”.

Note that both the Left and Right functions must be qualified by Microsoft.VisualBasic; the actual code to reference to the Left function should be as follows:

Microsoft.VisualBasic.Left(MyString, Number)

Tip
If you encounter a design time error when coding a built-in function and you are sure the function name is correct, try to qualify the name with Microsoft.VisualBasic. The error may be caused by name conflicts. Examples of built-in functions requiring the qualifier include Left, Right, Timer, and Day.

Asc and Chr Functions

The Asc function returns the ASCII key code value of a character. For example, the ASCII key code value for A is 65; therefore, Asc(”A”) will return a value of 65. The Chr function converts a key code value to a character and can be considered the complement of the Asc function. Chr(65) returns a character A.
What do you need this pair of functions for? These functions provide a convenient way to perform computation on characters, which can become pretty tedious otherwise. For example, suppose you are developing a Scrabble game. You probably would need to provide a capability to generate a string of random letters. The Chr function makes this fairly easy.
You know there are 26 letters in the English alphabet; therefore, you need to generate a random number within the range of 26 so that each number will correspond to a letter. The following code should accomplish this:

Dim Rand As New Random() Rand.Next(0, 26)

Recall that the Next method of the Random object returns an Integer number greater than or equal to the first argument but less than the second argument. The second statement should return an integer in the range of 0 and 25. Because A has an ASCII value of 65, adding 65 to the result of the Next method should produce the ACSII value of the random letter. You can then use the Chr function to convert this ASCII value to display the letter.

MsgBox(“The next random letter is “ & Chr(Rand.Next(0, 26) + 65))

As another illustration, suppose you want to display the next letter following the one that the user has entered in a text box named txtLetter when the user clicks a button named btnNext. What code will you provide in the button’s Click event procedure? You will first obtain the keycode value of the current letter (using the ASC function). Add 1 to that value to get the keycode value of the next letter and then convert the result to the letter (using the Chr function). The code can appear as follows:

Private btnNext_Click(ByVal Sender As System.Object, ByVal e As System.EventArgs) Handles btnNext.Click Dim KeyAscii As Integer ‘Get the ASCII value of the letter KeyAscii = Asc(txtLetter.Text) MsgBox(“The next letter is “ & Chr(KeyAscii + 1)) End Sub

In this illustration, you assume the user will not enter the letter Z or more than one letter in the text box.
The preceding discussion deals with the ASCII code. If you are dealing with characters in Unicode code, the proper functions to use are the AscW and CharW functions. The only difference between these two functions and the two just discussed is that the AscW and ChrW pair deals with the Unicode (two bytes), while the Asc and Chr pair deals with the ASCII code (one byte).

Val and Str Functions

The Val function converts a string into a numeric value. For example, Val(”123”) will return a value 123. The Str function does the opposite. It converts a number into a string. For example, Str(123) will return a string “ 123”. Note that there is a leading blank space before the string “123”. This can be important if you intend to check the length of the resulting string. If you do not want the leading blank space for any reason, you should use the Format function instead. For example, Format(123,''General Number'') will return a string “123”.
Note that the Val function ends its attempt to convert a string as soon as it encounters a nonnumeric character, thus Val(”1B2”) will return 1 with no error. In addition, Val(”3,456”) will return a value 3; however, CLng(''1B2 '') will result in an error, whereas CLng(''$3,456'') will return a value of 3456. In a text box, such as, txtUnitsSold, you may expect that the user will enter numbers with commas; therefore, one of the conversion functions should be used. You may also anticipate that the user will leave the box blank or enter an invalid string. In such a case, the Val function will be safer. Thus, you are faced with a dilemma of choosing the appropriate function to use. One possible solution is to use yet another function to decide which function to use. The function IsNumeric(S) can be used to test whether the string parameter S is a valid numeric string. If it is, the function returns a value True; otherwise, False. Your solution can look like the following:

If IsNumeric(txtUnitsSold.Text) Then UnitsSold = CLng(txtUnitsSold.Text) Else UnitsSold = Val(Val(txtUnitsSold.Text)) End If

You can even insist that the user enter a valid number before accepting the data. In this case, your code in the Else block will be a message requesting the user to enter a valid number.

LCase and UCase Functions

The LCase function returns a lowercase string. For example, LCase(”ABC”) will return a string “abc.” The UCase function returns the uppercase string, so UCase(”abc”) will give “ABC”.

Space Function

The function Space(n) will generate a string with n blank spaces.

Left, Right, and Mid Functions

The Left, Right, and Mid functions deal with the substring of a string. Left(S, n) returns the first n characters of the string S; therefore, Left(”Upper”,2) returns “Up”. Note that this function has a name conflict with the Left property of the form. To differentiate properly between this function and the Left property, this function must be coded as:

Microsoft.VisualBasic.Left(S, n)

Right(S, n) returns the last n characters in string S; therefore, Right(”Upper”,3) will return “per.” Note that this function also has a name conflict, and must be qualified with Microsoft.VisualBasic. The Mid(S, b, n) returns a string of n characters in S beginning from the bth position. Mid(”Upper”, 2, 3) will return “ppe”. If the third parameter is omitted, all the remaining string starting from the bth position will be returned. For example, Mid(”Upper”, 2) will return “pper”.
Mid can also be used as the target of a string assignment. For example, assume the string variable MyStr contains a string “Uppercase.” The following code will change the string to “Upperhand”:

Mid(MyStr, 6, 4) = “hand”

In this statement, the four characters in MyStr starting from the sixth position are replaced with a string “hand”. The last argument in Mid is an optional argument. If it is omitted, either the remaining length of MyStr or the length of the expression on the right side of the assignment (whichever is shorter) is used. The following table summarizes the examples discussed concerning these functions.

Code Result (Value of A)
A = Microsoft.VisualBasic.Left(''Upper'', 2) “Up”
A = Microsoft.VisualBasic.Right(''Upper'', 3) “per”
A = Mid(''Upper'', 2, 3) “ppe”
A = Mid(''Upper'', 2) “pper”
A = ''Uppercase'' ''Uppercase''
Mid(A, 6, 4) = ''Hand'' “UpperHand”

The InStr and InStrRev Function

The InStr(S, ss) function returns the position in S where its substring matches the string ss. For example, InStr(''ABCDE'', ''CD'') will return a value 3. Actually, the complete syntax for the function is as follows:

InStr([p], S, ss, [Compare])

where p = the position in S at which to begin the search
S = the string to be searched on
ss = the substring to search for
Compare = a value to specify the type of comparison and should be either CompareMethod.Text or CompareMethod.Binary. If CompareMethod.Text is specified, the search is not case sensitive; that is, “abc” and “ABC” are treated as equal.
Using this syntax, the expression InStr(''12-31-1999'', ''-'') will return a value 3 and the expression InStr(4, ''12-31-1999'',''-'') will return a value 6.
The InStrRev function has the following syntax:

InStrRev(S, ss, [p], [Compare])

where all the parameters have exactly the same meaning as those parameters in the InStr function. The positions in which the parameters are placed in the two functions are different, however. Also note that to specify the fourth parameter for the InStr function, you must also provide the value for the first parameter, as shown in the second through fifth code examples in the following table.


Code
Result(Value of Pos)
Pos = InStr(“Containing”, “in”) 6
Pos = InStr(1, “Containing”, “in”) 6
Pos = InStr(7, “Containing”, “in”) 8
Pos = InStr(7, “Containing”, “In”) 0
Pos = InStr(7, “Containing”, “In”, CompareMethod.Text) 8
Pos = InStrRev(“Containing”, “in”) 8
Pos = InStrRev(“Containing”, “In”,, CompareMethod.Text) 8

These functions and the substring functions (Left, Right, Mid) together form a very useful group of functions in parsing strings. An illustration is provided in the next subsection.

The Len Function

The Len function returns the length of the string, including blank spaces. The string “” containing nothing between the quotes has a length zero; therefore, Len(“”) will return a value of 0.

Tip
If you need to check whether a string (say, MyStr) is of zero length, your code is more efficient with:
If Len(MyStr) = 0 Then
than with:
If MyStr = “” Then

Trim, Ltrim, and Rtrim Functions

If you are interested only in the length of the visible characters in a string, you can use the Trim function to trim off the spaces and obtain the length accordingly. Len(Trim(MyString)) gives the length of the string with no leading or trailing spaces. If you are interested in trimming off only the leading spaces of any string, you can use the LTrim function to do the job. Furthermore, if you are interested in trimming off only the trailing spaces, you should use the RTrim function.

Look It Up
Search the Contents tab of the help file. Expand the following items (book icons) in sequence: Visual Studio .NET -> Visual Basic and Visual C # -> Reference -> Visual Basic Language -> Visual Basic Language and Run-Time Reference -> Keywords and Members by Task; then locate and click String manipulation keywords summary. You will find a list of functions organized by purpose and use. These functions can make your job of manipulating strings much easier. You should find Replace, Split, as well as those format functions useful.
Last change: February 13 2016 18:47:36.
<<PreviousNext>>