Doing Strings in VB Part 1

Submitted on: 1/18/2015 1:43:00 AM
By: TeknikForce (from psc cd)  
Level: Beginner
User Rating: By 4 Users
Compatibility: VB 6.0
Views: 319
     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.


Doing Strings In VB

Doing Strings In VB Part 1
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 your program.

Strings are an indispensable part of almost all VB software; you will need to use strings in almost all the software you ever make.

Let’s 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. Here’s 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. Here’s sample code that does that

Dim MyFileText 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 File

Open "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. I’ve 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.

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

Close #1 ‘Closes The File
This statement closes the file and frees file number 1. It’s a good practice to close the file immediately after you’ve 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 there’s a special case which forced me to rack my brains for quite a while when I was new to programming.

VB won’t 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.

Write #FileNumber, TheText
Print #FileNumber, TheText

Searching Stuff in Strings
You may often need to search for a word in lengths of text. Visual Basic’s Instr function does this great.

Dim WordPos
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 variable.

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, that’s 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 won’t 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 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.

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 won’t have made Left & Right if they weren’t supposed to be used.

TheText = Left(MyText,NoOfCharacters)
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 "ABC".

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.

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

Replacing Text In Strings
You can include this feature in your software using the Left, Right, Mid and Instr functions. Let’s see some sample code which ‘B’ with ‘F’ in a string ABCD in this fashion.

Dim TheText as String = "ABCD"
Dim WordPos as Integer
Dim MyTextLeft as String
Dim MyTextRight as String

First find the text using Instr
WordPos = Instr(TheText, "B") ‘returns 2

Use Left to take text before the searched character or word
MyTextLeft = Left(TheText, WordPos-1)

Use Right to take text after the searched character
MyTextRight = Right(TheText, len("ABCD")-WordPos)
MyTextRight = Mid(TheText,WordPos+len("B"),len(TheText)-WordPos+len("B"))

Put The Two Strings Together with the replaced character
TheText = 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 deleted.

Replacing Easily
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

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.

Encyrpting Strings
If you’ve 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. Here’s a Function Which Encrypts text using the numerical keys provided by the user.

Public Function 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 & "."
End Function

This extremely small function uses the unique features of Xor to provide good quality Encryption. First the ASCII value of the character is Xor’d with Key1 and then the resultant value is Xor’d with Key2 resulting in a random number that’s 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.

Public Function 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), Key1))
TheText = Mid(TheText, PeriodPos+1)
Exit Do
End Function

There’s 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 won’t be covering all that in this article. If you found this of any help please drop me a mail and I’ll 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 looks.

SearchPos = instr(1,"ABCD","C",vbTextCompare)

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. 


Other 4 submission(s) by this author


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Beginner category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)

Other User Comments

 There are no comments on this submission.

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)

To post feedback, first please login.