Listing 1a. The CompressOrDecompress function does the bulk of the work.
' Compress or decompress a text string.
Public Function _
CompressOrDecompress(ByVal input_text As String) _
As String
' Dims omitted
' Initialize the dictionary.
dictionary = _
" e as tinthouerhet anreesr d " & _
"onn or o i y wo tontyo. neisarte" & _
"ed, ctiy bat snd fal pensestve" & _
"ngitu talehaurllcousa mf dfoof " & _
"siril hmeg om Icehironsasiossbe" & _
"depe rli Tetel nicho lilprcactut" & _
"Thpaeceachh wige ebuaisursulmawa" & _
"otowtsmploI solyee Cunm rtieno S" & _
"diwhs.rafincademe.irplk ury Pwo" & _
"acos gams,duayavucColamowe Aoopu"
' If the first character has ASCII value 255,
' this is a compressed string.
If Left$(input_text, 1) = Chr$(255) Then
' Remove the first character.
input_text = Mid$(input_text, 2)
output_text = "" ' Start with a blank output.
For pos = 1 To Len(input_text) ' examine each char
ch_value = Asc(Mid$(input_text, pos, 1))
' See whether the ASCII value is greater than 95.
If ch_value > 95 Then
' This is the code in the dictionary for the two
' chars starting at pos. 2 * (ch_value - 96) + 1.
output_text = output_text & _
Mid$(dictionary, (ch_value - 96) * 2 + 1, 2)
CompressOrDecompress = input_text
Else ' This is the ASCII value of a char minus 32.
output_text = output_text & Chr$(ch_value + 32)
End If
Next pos
Else
' This is a normal string. Compress it. Start with
' Chr$(255) to indicate a compressed string.
output_text = Chr$(255)
pos = 1
Do While pos <= Len(input_text)
' Consider the two chars at pos and pos + 1.
pair = Mid$(input_text, pos, 2)
' See whether we've passed the end
' of the input string.
If Len(pair) < 2 Then ' We have.
' Set dict_pos = 0 to save this char unencoded.
dict_pos = 0
Else ' Find this pair in the dictionary.
dict_pos = InStr(dictionary, pair)
Do While dict_pos > 0
'If pair is here, see whether it's at an odd index.
If dict_pos Mod 2 = 1 Then Exit Do
' The pair is at an even position.
dict_pos = InStr(dict_pos + 1, dictionary,_
pair)
Loop
End If
' Add the pair's code or the first char to the output.
If dict_pos > 0 Then ' The pair is in the dictionary
output_text = output_text & _
Chr$((dict_pos - 1) \ 2 + 96) ' Move past pair
pos = pos + 2
Else ' The pair isn't in the dictionary.
' Add the first character to the output.
output_text = output_text & _
Chr$(Asc(pair) - 32)
' Move past the first char in the input text.
pos = pos + 1
End If
Loop ' Do While pos <= Len(input_text)
End If ' End if decompressing ... else ...
CompressOrDecompress = output_text
End Function
|