Page 1 of 1

Visual Basic 6 Library Functions – String Type Basic Knowledge of these functions Rate Topic: ***** 1 Votes

#1 Xenon   User is offline

  • Connection failed
  • member icon

Reputation: 9
  • View blog
  • Posts: 1,595
  • Joined: 12-September 05

Posted 04 November 2005 - 06:16 AM

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 :-

Consider the following example :-
Print UCase(“hello world”)

The output would be HELLO WORLD.

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 .
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:-

Consider this:
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.


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:
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.
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.

Left(string, no-of characters)
Right(string, no-of characters)

Now consider the following example code.
Dim Pname As String
Pname = “Samuel Williams”
Print Left(Pname, 6)
Print Right(Pname, 8)

The above code produces the result:



The first word Samuel is printed because of the statement
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:
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.

Mid(String, start-position, no-of-characters)

for example, the following 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:

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.
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.
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.
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.

InStr([start],string1,string2,[Compare])  ‘[ ] means optional.



Is a numeric expression that sets the starting position for each search, if omitted, the search begins at the first character of the string.

Is the String in which to search.

Is the string to be searched for in the “string1” string.

Specifies the type for string comparison. “0” for case sensitive search and “1” for case insensitive search.

Bringing to your attention:


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.
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


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.

‘Number argument is the number of spaces you want in the string.

Consider the following example 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.
‘Number >> number of characters to be repeated
‘character is the character to repeat
‘or you can also input character code

ForExample, the following code
sResult = String(10,65)
‘65 is the character code for uppercase “A”

will return “AAAAAAAAAA”

Now consider this :
Dim MyString
MyString = String(5, “*”)    ‘Returns “*****”

‘Character code for “*” is 42
MyString = String(5, 42)    ‘Returns “*****”

MyString = String(10, “ABC”) ‘ returns “AAAAAAAAAA”
Print MyString


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.
‘The Required number argument is a long containing any valid numeric expression.


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.
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


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”.
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

where the required charcode argument is a Long that identifies a character.


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:
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

Is This A Good Question/Topic? 1
  • +

Replies To: Visual Basic 6 Library Functions – String Type

#2 Xenon   User is offline

  • Connection failed
  • member icon

Reputation: 9
  • View blog
  • Posts: 1,595
  • Joined: 12-September 05

Posted 05 November 2005 - 11:35 PM

erk ! error in this reply, plz read the next one

This post has been edited by Xenon: 05 November 2005 - 11:39 PM

Was This Post Helpful? 0
  • +
  • -

#3 Xenon   User is offline

  • Connection failed
  • member icon

Reputation: 9
  • View blog
  • Posts: 1,595
  • Joined: 12-September 05

Posted 05 November 2005 - 11:37 PM

Adding further to this tutorial, i'd like to post a programming exercise to implement the knowledge gained by this tutorial in form of some litle programs.
exercise 1
Create a simple program that will search for a word in a given line of text.
-Open Visual Basic, create a new form,
-set the
Caption = "Search For Words"
ScaleHeight = 2820
ScaleWidth = 9150

now build the following interface,

Posted Image

where the controls
-cmdSearch = command button name

-txtText = the name text box in which the main text is entered which is the big box in the interface.
its properties are set as.
- multiline = true
-scrollbars = vertical

-txtWord - the small text box in which the word to be search for is entered.
-chkIgnore -case ignore checkbox option

here's the code try to follow it by the captions in it, it'd be better if you copied and pasted in VB and then try to follow the logic of the code by actual working of the program.

open the code window, and add this code for the click event of the command button cmdVerify.
Private Sub cmdSearch_Click()
Dim Lenmain As Integer, lenword As Integer, word As String
Dim freq As Integer
If txtWord.Text = "" Then
MsgBox "Enter the word to search for !"
Lenmain = Len(txtText.Text)
lenword = Len(txtWord.Text)
Print ""
Print "--------------------------------------------"

For a = 1 To Lenmain
'Extract word starting from ath position of lenword characters
word = Mid(txtText, a, lenword)
If chkIgnore Then
' this is when case is ignored

If LCase(word) = LCase(txtWord.Text) Then
' increase the value of occurence
freq = freq + 1
' Print the Occurence of the word, that is, at which character
Print "The word : "; txtWord; " has occured in the text at "; a; " character and onwards"
' ending the case ignore word search tree
End If

' case sensitive search
If word = txtWord.Text Then
freq = freq + 1
Print "The word : "; txtWord; " has occured in the text at "; a; " character and onwards"
' ending the case sensitive word search tree
End If

' ending the ignore case If End If tree
End If
'Ending the search loop
Next a
'Now print the total no of occurences
Print "---------------------------------------------"
Print "Total no of occurence of word is :"; freq
End If
End Sub

if you need further explanation, just add a reply here and ill try to explain it with further details.

Hope this was useful :)

Attached File(s)

Was This Post Helpful? 0
  • +
  • -

#4 Xenon   User is offline

  • Connection failed
  • member icon

Reputation: 9
  • View blog
  • Posts: 1,595
  • Joined: 12-September 05

Posted 06 November 2005 - 07:55 AM

exercise 2
Create an application that will reverse the entered string input. DO NOT use the StrReverse() function.

-this add on will help you to understand the working of the strReverse() function.
now build the following interface.
Posted Image
where the controls are
TextBox txtRev - the lower textbix in the form, which displays the reversed string

TextBox txtStr - input string box.

CommandButton cmdReverse - the code is the click event of this button.
Private Sub cmdReverse_Click()
Dim strl As String
Dim length As Integer
Dim ctr As Integer
txtRev.Text = ""
strl = txtStr.Text
length = Len(strl)

For ctr = length To 1 Step -1
txtRev.Text = txtRev.Text + Mid(strl, ctr, 1)
Next ctr
End Sub

the working
we use a For -- Next loop to achive our goal.
-First of all we feed the input string value to the string variable strl.

-Secondly, we store the length of the string in the length variable.

-next, we start the for loop, in which we start the loop in a reverse way.
that is we go from the last character of the string to the first.

-everytime, we extract ONE character using the MID function and put it in the textbox, one after the other in the line
txtRev.Text = txtRev.Text + Mid(strl, ctr, 1)

also notice the begining of the for loop
For ctr = length To 1 Step -1

step - 1 makes the for loop go one value less than the previous one every time, so the function takes the string backwards.
this is the same logic on which the StrReverse function works.

Kode LogiK
Was This Post Helpful? 0
  • +
  • -

#5 Xenon   User is offline

  • Connection failed
  • member icon

Reputation: 9
  • View blog
  • Posts: 1,595
  • Joined: 12-September 05

Posted 06 November 2005 - 08:04 AM

here are some more functions that i forgot to mention....equally useful.

13. Replace Function

this function returns a string in which a specified sub-string has been replaced with an another substring a specifed number of times.

The SynTax is:-

where the expression:


Expression : required argument. It is the String expression containing substring to replace.

Find : required argument. It is the substring being searched for.

Replace : required argument. It is the replacement substring.

Start : optional argument. It Specifies the position within expression where substring search is to begin. If omitted, the default is 1.

Count : optional arugment. It specifies the number of substring substitutions to be performed. If omitted , the default value is -1, which implies all possible substitutions.

Compare : optional argument. It is the numeric value indication the kind of comparision to use when evaluating subsstrings.
Constant  Value  Description

vbUseCompareOption  -1 Performs a comparison using the setting of Option Compare statement.
vbBinaryCompare    0 Performs a binary comparison.
vbTextCompare    1  Performs a text compare, case-ignore.
vbDatabaseCompare  2  used in MSACESS only. Information based search.

Return Values

Replace returns the following values


If    Return Value
expression is zero length zero length string ("")
expression is null  error occurs
Find is zero length  copy of expression argument
Replace is zero length  copy of expression with all occurences of Find removed.

Start > len    Zero Length String.
Count is 0  Copy of expression.

14. StrComp Function
This Function returns a integer value after the comparison of two string expressions.

its syntax is :



string1- optional. the first compare string.
string2- optional. the second compare string.
compare - type of comparison to make between these strings.

compare values are of 4 types.
value    description
0        binary comparison case sensitive.
1        textual comparison case insensitive.
2        MSACCESS database information based comparison.

the return value can be of 4 types.


value    description
-1 -      if string1 is lesser than string2
0 -        both strings are equal
1          string1 greater than string 2.
Null -    both strings are null.

Was This Post Helpful? 0
  • +
  • -

#6 karankochhar25   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 17-September 07

Posted 17 September 2007 - 02:23 AM

I want this
Was This Post Helpful? 0
  • +
  • -

#7 thava   User is offline

  • D.I.C Lover
  • member icon

Reputation: 180
  • View blog
  • Posts: 1,607
  • Joined: 17-April 07

Posted 24 October 2008 - 11:06 PM

can any one make this as a bunch ;) ;) ;)
Was This Post Helpful? 0
  • +
  • -

#8 walidzak   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 14-July 08

Posted 19 February 2009 - 10:17 AM

it is a great

Was This Post Helpful? 0
  • +
  • -

#9 Guest_Kate*


Posted 08 August 2010 - 01:49 AM

thanks. this is very helpful.
Was This Post Helpful? 0

#10 NeoTifa   User is online

  • NeoTifa Codebreaker, the Scourge of Devtester
  • member icon

Reputation: 4601
  • View blog
  • Posts: 19,316
  • Joined: 24-September 08

Posted 10 August 2010 - 07:32 AM


‘Returns “A

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1