江蘇省二級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 |