Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

Chapter 13 Exploring Text Files and String Processing 335


The entire SortTextToolStripMenuItem_Click event procedure looks like this:

Dim strArray() As String
Dim sText As String
Dim i As Short

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)

'sort array
ShellSort(strArray, strArray.Length)

'then display sorted array in text box
sText = ""
For i = 0 To strArray.Length - 1
sText = sText & strArray(i) & vbCrLf
Next i
txtNote.Text = sText
txtNote.Select(0, 0) 'remove text selection
The Split method creates an array that has the same number of elements as the text
box has lines of text. After the array is full of text, I call the ShellSort procedure located
in the Module1 .vb module, which I discussed earlier in this chapter. After the array is
sorted, I use a For loop (as discussed in Chapter 7) to reconstruct the lines and copy
them into the text box.


  1. Display the code for the Module1 .vb module in the Code Editor.


This module defines the content of the ShellSort procedure. The ShellSort procedure
uses an If statement and the <= relational operator (as discussed in Chapters 6, 8,
and this chapter) to compare array elements and swap any that are out of order.
The procedure looks like this:

Sub ShellSort(ByVal sort() As String, ByVal numOfElements As Short)
Dim temp As String
Dim i, j, span As Short
'The ShellSort procedure sorts the elements of sort()
'array in descending order and returns it to the calling
'procedure.

span = numOfElements \ 2
Do While span > 0
Free download pdf