Doing Strings in VB Part 1
Strings play an important role in every software. This tutorial is big, it has everything that a beginner wants. This version is modified to remove some mistakes in the previous one, and adds some information about instr. I'd be glad to see your feedback. Thanks! Note: Since I am no guru, this could be all wrong, use it at your own risk.
Original Author: Cyril Gupta
Code
Doing Strings In VB Part Strings are an indispensable Lets start with Strings in a file Dim MyFileText Open MyFileText = The first argument of Input$ is Lof(1). Close #1 Problems with Opening File VB wont recognize and read Writing Strings to Files Write Searching Stuff in Strings Dim WordPos Here WordPos holds the position The first argument The second argument The third argument The fourth argument VbTextCompare is inferior to If Instr is successful in Extracting parts from a VB Pros and Code invigilators TheText = Right returns the specified MyText = Replacing Text In Strings Dim TheText as First find the text using Instr Use Left to take text before the Use Right to take text after the Put The Two Strings Together The Modus Operandi here is quite Replacing Easily Here the first argument is the Encyrpting Strings Public Function This extremely small function Public Function Theres still a lot more to Searching for Stuff SearchPos Most of you should already be familiar with the Thanks
content="text/html; charset=iso-8859-1">
1
By Cyril Razoredge Gupta
Mail: cyril@icnol.comface="Verdana">
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
your program.
part of almost all VB software; you will need to use strings in
almost all the software you ever make.
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.
You may often need to store and retrieve text from a file.
Heres how
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
To MyFileText
Close #1 Closes The Filesize="2" face="Verdana">
"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 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
MyFileText.
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.
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
programming.
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.
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.
#FileNumber, TheText
Or
Print
#FileNumber, TheText
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)
of the first character of the word if it is found in the file.
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.
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.
MyWord is the word or character that has to be
searched in MyText. MyWord can also be a string instead of a
variable.
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.
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.
finding a match it returns the position of the first character in
the word. If it is unsuccessful the function returns 0.
string
You may often to extract specific portion of a string and use
them. VB has three functions for extracting string parts. Left,
Mid & Right.
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
used.
Left(MyText,NoOfCharacters)
Left function retrieves
specified number of characters from the left of the specified
string for e.g. if you wrote size="2" face="Verdana">MyText = Left("ABCD",3)size="2" face="Verdana"> then left would give you
"ABC".
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.
Mid(TheText,StartPos,LenOfText)
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.
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
fashion.
String = "ABCD"
Dim WordPos as Integer
Dim MyTextLeft as String
Dim MyTextRight as String
WordPos =
Instr(TheText, "B") returns 2
searched character or word
MyTextLeft =
Left(TheText, WordPos-1)
searched character
MyTextRight
= Right(TheText, len("ABCD")-WordPos)
Or
MyTextRight
=
Mid(TheText,WordPos+len("B"),len(TheText)-WordPos+len("B"))
with the replaced character
TheText =
MyTextLeft & "F" & MyTextRight
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
deleted.
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
single line.
For e.g. if I want to replace all "BBBB" with
"C" I would use
Replace("BBBB","B","C")
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 & "."
Next
End 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
Do
PeriodPos = instr(TheText,".")
If Not PeriodPos=0 Then
TheXordNum=Mid(TheText,1,PeriodPos-1)
XorDecrypt = XorDecrypt & Chr(Xor(Xor(TheXordNum, Key2),
Key1))
TheText = Mid(TheText, PeriodPos+1)
Else
Exit Do
Endif
End Function
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.
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
looks.
= instr(1,"ABCD","C",vbTextCompare)
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.
Razoredge
E-mail: size="2" face="Verdana">psl@nde.vsnl.net.in
Loading Comments ...
Comments
No comments have been added for this post.
You must be logged in to make a comment.