Doing Strings In VB
Doing Strings In VB Part
By Cyril Razoredge Gupta
Warning: The code presented here is not indented properly because
HTML won't let me put a space or a tab character before the text.
Please indent the code if you plan to use the reuse the code in
Strings are an indispensable
part of almost all VB software; you will need to use strings in
almost all the software you ever make.
Lets start with
What is a string and where do you use it?
In VB String is a length of text assigned to a variable of type
Variant or of type String. A string can store a maximum of around
2 billion characters between ASCII value 32 to 256. Strings mean
a lot to a programmer. They can hold important data, which the
user reads, intermediate values, comments, or can be used simply
to test if the software works correctly. People store text in
strings in .INI files, in the windows registry .RES files and
other text resources.
Strings in a file
You may often need to store and retrieve text from a file.
Retrieving text from a file
VB6 and VB5 introduced the new File object handling system but
moldy programmers like me still prefer the old Open Statement.
Heres sample code that does that
As String Makes a String Variable Called MyFileText
Open "MYFILE.TXT" for input as #1 Opens The File
And Names It #1
MyFileText = Input$(Lof(1),1) Assigns The Text In The File
Close #1 Closes The File
"MYFILE.TXT" for Input as #1 Opens The File And
Names It #1
This line does the actual
opening bit. Myfile.Txt is the name of the file to be opened. You
can open a file in many ways for many purposes. Ive used
Input Mode here because I just want to read the contents of the
file. If you want to write to a file use Output, use
Append to add in the end of the file and Random if you have a
Database in the file. Binary Mode can be used to load Bitmap or
Sound Files. #1 is the number of the file. Whenever you want
to work on the file you will access it using that number.
Input$(Lof(1),1) Assigns The Text In The File To MyFileText
This line assigns the
contents of the file to MyFileText variable. Input$ Function
reads data from a file using the file number.
The first argument of Input$ is Lof(1).
The LOF function retrieves the length of a file in number of
characters. The second argument 1 is the number of file,
which has to be read. So in practice we tell VB to read the
entire length [LOF(1)] of file number 1 in the variable
Closes The File
This statement closes the
file and frees file number 1. Its a good practice to close
the file immediately after youve read the contents in a
variable to free resources and avoid problems caused by a file
that remains open all the while the software is running.
Problems with Opening File
For most problems VB gives a self evident error message which
documents in detail the problem and allows the error to be
trapped and rectified. However theres a special case which
forced me to rack my brains for quite a while when I was new to
VB wont recognize and read
a file with a null terminated string in the normal input mode. Now in most editors like
NotePad etc., no null terminated string is added at the end of
the file but in some special cases, specially when the files has
been used for Binary purposes there may be a null terminated
string at the end of the file, and the file has to be opened in Binary mode in
VB, if you try to open it in input mode, there will be some cryptic error.Rectifying this problem is quite easy, just remove the last
character from the file and it gets opened fine.
Writing Strings to Files
To put your string in a file use Output instead of Input to
open the file. To save your string into the file you can either
use Write # or Print # in this way.
Searching Stuff in Strings
You may often need to search for a word in lengths of text.
Visual Basics Instr function does this great.
WordPos = Instr(1, MyText, MyWord, VbTextCompare)
Here WordPos holds the position
of the first character of the word if it is found in the file.
The first argument
1 specifies the character no. from where Instr
should start looking. This is useful when you need to do multiple
searches or search from the middle of the text. You can also
leave this option blank if you want to search from the beginning
of the text.
The second argument
MyText specifies the name of the string variable
that has to be searched. You can also use a string length like
this one ("I can use This String Instead Of MyText")
instead of the variable.
The third argument
MyWord is the word or character that has to be
searched in MyText. MyWord can also be a string instead of a
The fourth argument
VbTextCompare decides the mode of the comparison.
By default the mode is Binary. Here I am doing a comparison
between two strings, thats why I have used VbTextCompare
instead of the default VbBinaryCompare.
VbTextCompare is inferior to
Binary compare in speed. In fact when I ran a test which tried
finding the letter A in a string comprising of all
alphabets VbTextCompare took twice the time needed by
VbBinaryCompare to finish the searches. However I still prefer
using VbTextCompare in most cases because VbBinaryCompare thinks
Capital A and small a are different
characters and wont provide a match if the case is
different in the searched word and original string.
If Instr is successful in
finding a match it returns the position of the first character in
the word. If it is unsuccessful the function returns 0.
Extracting parts from a
You may often to extract specific portion of a string and use
them. VB has three functions for extracting string parts. Left,
Mid & Right.
VB Pros and Code invigilators
recommend using Mid for all types of extraction. It is entirely
possible to do almost everything with Mid, but they wont
have made Left & Right if they werent supposed to be
Left function retrieves
specified number of characters from the left of the specified
string for e.g. if you wrote MyText = Left("ABCD",3) then left would give you
Right returns the specified
number of characters from the rightmost part of the string.
Mid is by far the most versatile, useful function which can serve
the function of both Left, Right and also extract text from the
middle of the document.
The first argument
TheText is the name of the string from which the text
has to be extracted.
The second argument StartPos is the character
position from which Mid should start taking the text.
The third argument LenOfText is the no of characters
that have to be picked up.
Replacing Text In Strings
You can include this feature in your software using the Left,
Right, Mid and Instr functions. Lets see some sample code
which B with F in a string ABCD in this
Dim TheText as
String = "ABCD"
Dim WordPos as Integer
Dim MyTextLeft as String
Dim MyTextRight as String
First find the text using Instr
Instr(TheText, "B") returns 2
Use Left to take text before the
searched character or word
Use Right to take text after the
= Right(TheText, len("ABCD")-WordPos)
Put The Two Strings Together
with the replaced character
MyTextLeft & "F" & MyTextRight
The Modus Operandi here is quite
simple. We look for the string in the text, take all the text
that is prior to the string with the left function, and all the
text that is present after the string using the Right or Mid
function. The two strings are then put together with the
replacement text or no text if the part of the string has to be
If you were intimidated by the long length and seemingly
complex code, you can do this much more easily if you have VB6.
The new Replace function eliminates several lines of code with a
For e.g. if I want to replace all "BBBB" with
"C" I would use
Here the first argument is the
original text, Second is the text to be searched and the third is
the alternative text.
You can also specify the number of found words to be replaced
using an extra Count argument, i.e. set count as 1 if you want to
replace only the first find and none other or leave it to the
default to replace all finds.
If youve ever though about storing passwords or other
sensitive data in a file or a string you must have thought
Encrypting it. Several algorithms of encryption exist in the
market and some of them are very complex. You can make a simple
algorithm of your own by replacing the ASCII value of the
characters, however the approach provides a weak form of
encryption and can be broken very easily. However you can do
quality encryption very easily using the VB Xor function.
Heres a Function Which Encrypts text using the numerical
keys provided by the user.
XorEncrypt(Byval TheText As String, Byval Key1 As Integer, Byval
Key2 As Integer) As String
For I = 1 to Len(TheText)
XorEncrypt = XorEncrypt & Asc(Mid(TheText, I, 1)) Xor Key1
Xor Key2 & "."
This extremely small function
uses the unique features of Xor to provide good quality
Encryption. First the ASCII value of the character is Xord
with Key1 and then the resultant value is Xord with Key2
resulting in a random number thats very hard to decrypt,
the number is delimited by the period sign to distinguish two
characters from each other. Xor performs a bitwise calculation.
If you perform a Xor on two numbers and then Xor the resultant
figure with any of the two numbers Xor returns the other number.
XorDecrypt(Byval TheText As String, Byval Key1 As Integer, Byval
Key2 As Integer) As String
Dim PeriodPos as Integer
PeriodPos = instr(TheText,".")
If Not PeriodPos=0 Then
XorDecrypt = XorDecrypt & Chr(Xor(Xor(TheXordNum, Key2),
TheText = Mid(TheText, PeriodPos+1)
Theres still a lot more to
strings, in fact a lot-lot more, we could talk about storing
Strings in .INI files, strings in registry, strings in Random
Access Files, Strings Compiled in .EXEs with resources and a
whole lot of other types of strings, but, I guess we wont
be covering all that in this article. If you found this of any
help please drop me a mail and Ill try to write all the
other parts as quick as possible.
Searching for Stuff
The most common functionality needed by any user is searching. You can use
the 'Instr' statement for performing searched in VB. This is how a typical instr
Most of you should already be familiar with the
instr statement, so I am not going to explain it here. The thing that needs a
though is the last parameter, vbTextCompare. What parameter you pass to this
option decides how fast your search will be. If you use vbTextCompare, instr
ignore case and search strings in both upper case and lower case, but the speed
will be slowed tremendously. If you use vbBinaryCompare, it speeds up the search
more than 10 times, but will match case will searching. Personally I recommend
you use vbBinaryCompare, if you can, the speed gained is tremendous.