Visual Basic 6 Library Functions – String Type
These are the Built in Functions provided by Visual Basic. VB offers a rich set of built-in-functions for manipulating strings, numbers, dates and time. Built in functions are important and useful as they cut down effort and time, if one has to write the entire program all over. This tutorial is going to cover some of the important and commonly used string functions available in the Visual Basic Library.
String Functions
The string functions allow you to work with strings in numerous ways such as changing cases, extracting characters from a string, determining whether a character is a part of a string etc. etc.
1. The LCase and UCase Functions
these two functions convert strings to all lower or all upper case. The LCase( ) functions converts a string into all lower case and UCase( ) does exactly the opposite. These functions might be useful if you want to compare strings.
The Syntax would be :-
CODE
LCase(String)
UCase(String)
Consider the following example :-
CODE
Print UCase(“hello world”)
The output would be HELLO WORLD.
Similarly,
CODE
Print LCase(“StuDEnts”)
Will produce string students.
Note that both the functions work ignorant of the fact whether the string has upper or lower case characters or not. They simply convert all the characters to upper or lower case respectively.
Now consider the following example.
Example 1.1
Obtain text from textbox txtLocation and determine whether the user lives on Earth or not. Remember that the user can enter the location in any possible case combination. You should be able to compare with all cases .
CODE
Private Sub txtLocation_Change( )
Dim Loc As String
Loc = “earth”
If UCase(txtLocation.Text) = UCase(Loc) then
MsgBox “So you live on earth, welcome humanoid! ”
End if
End sub
Essential Fact:
Note that it is essential for both stings to be equal in case as WELL as in LENGTH. Try running the Above code with a trailing blank in the text box, you wont get any result. Handling such problems is discussed further in the tutorial. You can also use LCase function (on both sides of course) instead of the UCase function that has been used in the above example. Always remember that you can compare strings in two ways; case – ignorant or non ignorant, depending on the need.
2. The Len Function
This Function gives you the length of the string i.e. how many characters long the string is. All the characters are counted ( punctuation, numbers, alphabets, special characters and blank spaces. Etc)
The Syntax is:-
CODE
Len(String)
Consider this:
CODE
Dim sAddress As String, iResult as Integer
sAddress = “125 Princeton Street”
iResult = Len(sAddress)
After the above code is executed the variable iResult stores the value 20 , which is inclusive of the blank spaces in the sAddress variable.
This function can be used very effectively in allowing minimum and maximum length for a value. For example, a password field may have a minimum of 6 characters and a maximum of 20 characters, and this can be verified by the Len( ) Function.
3. The Trim, LTrim and RTrim Functions.
These functions remove leading (LTrim function) or trailing(RTrim Function) from a string. These functions don’t affect any spaces between words. The Trim( ) function simply accomplishes both LTrim( ) and RTrim( ) function, i.e. removes all leading and trailing blanks.
Syntax
CODE
LTrim(String)
RTrim(String)
Trim(String)
Users may inadvertently type spaces into a text box, and you can use these functions to account for that, but mostly the Trim( ) function is used with fixed-Length strings, user defined types, and Random Access Files.
Now consider the following code example:
CODE
sResult = LCase(Trim(“ EXCEL “)
the variable sResult will store the value “excel” in it. Here we’ve used a function as an argument for another function. This is commonly done and an efficient way to program.
Now let’s re-write the program of example 1.1
This time note that the blank spaces in front or back of text should not affect the result.
CODE
Private Sub txtLocation_Change( )
Dim Loc As String
Loc = “earth”
If UCase(Trim(txtLocation.Text)) = UCase(Loc) then
MsgBox “So you live on earth, welcome humanoid! ”
End if
End sub
See, now the code works irrespective of the blank spaces in front or back of the main text.
4. Left and Right Functions
These are two functions that are used to extract a certain number of characters from the leftmost or rightmost portions of a string. These functions require two arguments L the original string, and the number of characters to extract from that string.
Syntax:
CODE
Left(string, no-of characters)
Right(string, no-of characters)
Now consider the following example code.
CODE
Dim Pname As String
Pname = “Samuel Williams”
Print Left(Pname, 6)
Print Right(Pname, 8)
The above code produces the result:
QUOTE
Samuel
Williams
The first word Samuel is printed because of the statement
CODE
Print Left(Pname, 6)
see that it has been assigned to take the Pname string containing “Samuel Williams” and extract 6 leftmost characters from it. Similarly the code:
CODE
Print Right(Pname, 8)
extracts 8 rightmost characters from the Pname string.
5. Mid Function and Mid Statement.
Mid function is used to extract characters from the middle of a string, we need three arguments here: the Original String, the place to Start Extracting characters, and the number of characters to extract.
Syntax
CODE
Mid(String, start-position, no-of-characters)
for example, the following code :
CODE
Print Mid("Green Day Rocks", 7, 3)
will print “Day”, starting from the 7th character extracting 3 characters including the start position character. Try changing the start position and no of characters values in the function and notice the different results obtained.
Also note that all characters are included in the operation.
The Mid Statement not only extracts the characters, but also replaces them with the text you specify. Since this is a statement and not a function, you don’t get a result, rather the action is completed for you,
For example, in the following code, an unscrupulous person typed in the variable sInput that “Green Day Sucks”, you can change it to “Green Day Rocks” by the following Code:
CODE
sInput = "Green Day Sucks"
Print sInput
Mid(sInput, 11, 5) = "Rocks"
Print sInput
here we see that the position of “S” in “Sucks” is at 11 position from start, in the string “Green Day Sucks”, therefore we input “11” as start position to replace, and since there are 4 preceding unwanted characters, we input “5” as the total number of characters to be replaced. The ‘=’ character indicates by which string to replace which we write on the right hand side, which is “Rocks”
SEE the difference in the First Print and the second print. And by applying your own Kode LogiK, you can specify the start position, the number of characters to replace and the text to put in the original place.
Now consider an example that uses both Mid( ) function as well as Mid Statement.
-Write a function namely AltCap that receives a String argument and returns the string wherein each alternate character is in Uppercase.
Now add this code in the general declaration part of a form.
CODE
Public Function AltCap (ByRef sInput As String) As String
Dim i As integer, sCurrentChar As String
For i = 1 to Len(sInput)
sCurrentChar = Mid(sInput, i, 1) ‘Mid Function Used
if i Mod 2 = 0 then
Mid(sInput, i, 1) = LCase(sCurrentChar) ‘ Mid Statement Used.
Else
Mid(sInput, i, 1) = UCase(sCurrentChar) ‘ Mid Statement Used.
End If
Next i
AltCap = sInput
End Function
Now call the Function in a Command Button’s click( ) event.
CODE
Private Sub Command1_Click()
Dim myString As String
myString = "I want to be a leet"
myString = AltCap(myString)
Print myString
End Sub
The output would be produced as :
I WaNt tO Be a lEeT
Note that blank spaces are also “uppercased” in the function that we have used, which obviously doesn’t have any effect.
6. InStr Function
The InStr function searches for strings within strings.
Syntax
CODE
InStr([start],string1,string2,[Compare]) ‘[ ] means optional.
Where
QUOTE
Start
Is a numeric expression that sets the starting position for each search, if omitted, the search begins at the first character of the string.
String1
Is the String in which to search.
String2
Is the string to be searched for in the “string1” string.
Compare
Specifies the type for string comparison. “0” for case sensitive search and “1” for case insensitive search.
Bringing to your attention:
QUOTE
there are two ways to compare strings – case sensitive and case insensitive.
> case sensitive is a Binary Comparison
e.g. string “VB” and string “vb” are not equal in this case.
>case insensitive is a Text Comparison.
e.g. string “VB” and string “vb” are equal in this case.
By default VB6 will use the Binary method to compare strings unless explicitly specified.
Now Consider the Following Code.
CODE
Dim SearchString, SearchChar, MyPos
‘this is the String to Search in
SearchString = “the earth is the third planet in the Solar system”
‘this is the String to Search for
SearchChar = “S”
‘ Textual Comparison starting at position 1 returns 12
MyPos = InStr( 1,SearchString, SearchChar,1)
Print MyPos
‘ Binary Comparison starting at position 1 returns 38
MyPos = InStr( 1,SearchString, SearchChar,0)
Print MyPos
‘If you simply omit the compare and start argument, it will return 38
MyPos = InStr( SearchString, SearchChar)
Print MyPos
‘Now to search for a Sting that doesn’t exist.
MyPos = InStr( 1,SearchString,”X”,1)
Print MyPos
‘ ^^Returns ‘0’
InStr is a function and will return the position of the first occurrence of the search string . if the string is not found then it will return ‘0’.
Something more
QUOTE
InStrRev( ) is a related function here. It works similar to the InStr function, but it performs the search BACKWARDS.
7. Space Function
this function by itself produces a certain number of spaces.
Syntax
CODE
Space(number)
‘Number argument is the number of spaces you want in the string.
Consider the following example code.
CODE
Dim MyString
MyString = “HelloWorld”
Print MyString
‘ this line inserts 10 blank spaces in between ‘Hello’ and ‘World’
MyString = “Hello”& Space(10) & “World”
Print MyString
the best use of Space( ) is to clear fixed length strings.
sRecord = Space(128)
8. String Function
this function is used for producing a string with certain number of repeating characters.
Syntax
CODE
String(number,character)
‘Number >> number of characters to be repeated
‘character is the character to repeat
‘or you can also input character code
ForExample, the following code
CODE
sResult = String(10,65)
‘65 is the character code for uppercase “A”
will return “AAAAAAAAAA”
Now consider this :
CODE
Dim MyString
MyString = String(5, “*”) ‘Returns “*****”
‘Character code for “*” is 42
MyString = String(5, 42) ‘Returns “*****”
MyString = String(10, “ABC”) ‘ returns “AAAAAAAAAA”
Print MyString
QUOTE
Remember that no matter how long the string you enter in the character argument, it will always select the first character of that string. So entering “ABC” or “ABCDEFGH” wont matter much, as “A” will be selected in both cases.
9. Str Function
this function converts a number into equivalent string.
CODE
Syntax
Str(number)
‘The Required number argument is a long containing any valid numeric expression.
QUOTE
when numbers are converted to strings, a leading space is always reserved for the sign of number. If number is positive, then the returned string contains a leading space and the plus sign is implied, else a ‘-’ sign is put in front of the number.
The following example uses the Str Function to return a sting representation of a number.
CODE
Dim MyString
MyString = Str(1302)
Print MyString ‘Returns “ 1302”
MyString = Str(-12503.54)
Print MyString ‘Returns “-12503.54”
MyString = Str(234.007)
Print MyString ‘Returns “ 234.007”
10. Asc Function
This function is used to get a character’s equivalent ASCII code
Syntax
CODE
Asc(String)
QUOTE
Normally you would use a single character enclosed in quotes or one character resulting from another function, but using a multi character string doesn’t cause an error; the function will simply take the first character of the string.
For Example the following code will print 68, the ASCII code of character “D”.
CODE
sObject = “Donkey”
iResult = Asc(sObject)
Print iResult
11. Chr Function
This function returns a String containing the character associated with the specified character code.
The Syntax
CODE
Chr(charcode)
where the required charcode argument is a Long that identifies a character.
QUOTE
Numbers from 0 – 31 are the same as standard, non preintable ASCII codes. For example, Chr(10) returns a linefeed character. The normal range for charcode is 0 – 225. However on DBCS systems, the actual range for charcode is from -32768 to 65535.
Now consider the following example:
CODE
Dim MyChar
MyChar = Chr(65) ‘Returns “A”
MyChar = Chr(97) ‘Returns “a”
MyChar = Chr(62) ‘Returns “>”
MyChar = Chr(37) ‘Returns “%”
12. StrReverse Function
This Function returns a string in which the order of a specified string is reversed. Its Syntax is
CODE
StrReverse(String1)