江苏省二级VB常用算法(十)字符处理(统计与加密)- - |
VB常用算法(十)字符处理(统计与加密)- -曹苏群 http://caosuqun.bokee.com Tag: 统计 加密 字符处理 算法
1、算法说明1) 加密解密
最简单的加密方法是:将每个字母加一序数,例如5,这时: “A”→”F”,”a” →”f”,”B” →”G”,”b” →”g”……”Y” →”D”, ”y” →”d”,”Z” →”E”, ”z” →”e” 解密是加密的逆操作。 界面如下:
代码如下: Option Explicit
Private Sub Command1_Click() Dim strInput$, Code$, Record$, c As String * 1 Dim i%, length%, iAsc% strInput = Text1.Text length = Len(Trim(strInput)) Code = "" For i = 1 To length c = mid(strInput, i, 1) Select Case c Case "A" To "Z" iAsc = Asc(c) + 5 If iAsc > Asc("Z") Then iAsc = iAsc - 26 Code = Code & Chr(iAsc) Case "a" To "z" iAsc = Asc(c) + 5 If iAsc > Asc("z") Then iAsc = iAsc - 26 Code = Code & Chr(iAsc) Case Else Code = Code & c End Select Next i Text2.Text = Code End Sub
Private Sub Command3_Click() Text1.Text = "" Text2.Text = "" Text3.Text = "" Text1.SetFocus End Sub
2) 统计 问题提出 统计字符或者数字出现的次数。 算法说明 以字符统计为例,设基本问题如下: 请统计一段文本中英文字母在文本中出现的次数。(不区分大小写) 如:I am a student. 得到: A:2 d:1 e:1 I: 分析: 由于不区分大小写,因此可定义一个大小为26(下标:0-25)的数组,每个元素依次记录A、B、C…Z字母出现的次数。 A(0)存放字母a出现的次数 A(1)存放字母b出现的次数 A(2)存放字母c出现的次数 A(3)存放字母d出现的次数 … 譬如:aabdc
代码如下: Option Explicit Private Sub Command1_Click() Dim i As Integer, j As Integer Dim zimu(25) As Integer Dim allStr As String Dim aStr As String allStr = UCase(Text1.Text) For i = 1 To Len(Text1.Text) aStr = Mid(allStr, i, 1) If aStr >= "A" And aStr <= "Z" Then zimu(Asc(aStr) - Asc("A")) = zimu(Asc(aStr) - Asc("A")) + 1 End If Next i For i = 0 To 25 If zimu(i) <> 0 Then j = j + 1 Text2.Text = Text2.Text & Chr(i + Asc("A")) & ":" & str(zimu(i)) & " " If j Mod 5 = 0 Then Text2.Text = Text2.Text & Chr(13) & Chr(10) End If Next i End Sub
解题技巧 熟练运用字符处理函数,对于一些数论题,譬如逆序数等也可将数字通过CStr函数转换为字符后,利用字符处理函数来解题。 2、实战练习1) 补充代码(2003秋二(8)) 下面程序的功能是统计文件中英文字母(不区分大小写)出现的个数。 Option Base 1 Private Sub Command1_Click() Dim alpha(26) As Integer,n As Integer Dim i As Integer,s As String Open "c:\kav2003\readme.txt" For Input As #11 Do While Not EOF(11) s= (1) s=UCase(s) If s>="A" And s<="Z" Then n= (2) alpha(n)=alpha(n)+1 End If For i=1 To 26 If alpha(i)<>0 Then List1.AddItem Chr(i+64)&":"&CStr(alpha(i)) End If Next i Close End Sub
2) 补充代码(2000秋二(6)) 下面程序的功能是:统计当前盘当前文件夹中的顺序文件data.txt中共有多少个单词,约定连续出现的字母定义为一个单词。 Option Explicit
Private Sub Form_Click() Dim Char() As String, St As String, Tem As String Dim Idx As Integer, Js As Long, Flen As Long Dim F As Boolean, W As String * 1 (1) Flen = LOF(10) St = Input(Flen, #10) Js = 1 Do While Js <= Flen+1 W = Mid(St, Js, 1) If (2) Then Tem = Tem + W F = True ElseIf F = True Then Idx = Idx + 1 ReDim Preserve Char(Idx) Char(Idx) = Tem Tem = (3) F = False End If (4) Print "共有"; Idx; "个单词" For Js = 1 To Idx Print Char(Js) Next Js End Sub |