332 Part II Programming Fundamentals
Because the entire contents of a text box are stored in one string, the program must first
break that long string into smaller individual strings. These strings can then be sorted
by using the ShellSort Sub procedure, a sorting routine based on an algorithm created
by Donald Shell in 1959. To simplify these tasks, I created a module for the ShellSort Sub
procedure so that I can call it from any event procedure in the project. (For more about using
modules, see Chapter 10, “Creating Modules and Procedures .”) Although you learned how
to use the powerful Array.Sort method in Chapter 11, “Using Arrays to Manage Numeric
and String Data,” the ShellSort procedure is a more flexible and customizable tool. Building
the routine from scratch also gives you a little more experience with processing textual
values—an important learning goal of this chapter.
Another interesting aspect of this program is the routine that processes the lines in the text
box object. I wanted the program to be able to sort a text box of any size. To accomplish this,
I created the code that follows. The code uses the Replace, EndsWith, and Substring methods
of the String class. The Replace method is used to replace the different newline characters
(carriage return, line feed, or carriage return and line feed) with just the carriage return
character. The EndsWith method checks for a carriage return at the very end of the text.
The Substring method is used to remove the last carriage return if it exists:
sText = txtNote.Text
'replace different new line characters with one version
sText = sText.Replace(vbCrLf, vbCr)
sText = sText.Replace(vbLf, vbCr)
'remove last carriage return if it exists
If sText.EndsWith(vbCr) Then
sText = sText.Substring(0, sText.Length - 1)
End If
'split each line in to an array
strArray = sText.Split(vbCr)
This code also uses the very handy Split method of the String class. The Split method breaks
a string down into substrings and puts each substring into an array. The breaks are based
on a separator string that you specify (in this case, a carriage return). The resulting array of
strings then gets passed to the ShellSort Sub procedure for sorting, and ShellSort returns the
string array in alphabetical order. After the string array is sorted, I can simply copy it back to
the text box by using a For loop.
Run the Sort Text program
- Open the Sort Text project located in the C:\Vb10sbs\Chap13\Sort Text folder.
- Click the Start Debugging button to run the program.