用VB统计中英文字符个数
原理:遍历整个文本中的字符,返回它们的ASCII码值即可知道该字符是中文还是英文,然后统计即可达到目的。
启动VB,新建工程,在窗体加入一个文本框,将其OLEDropMode属性设置为1-Manual(手工),MultiLine属性设为true,ScrollBars属性为3-Both;再加入两个CommandButton控件,一个Name属性为Clearbtn,Caption属性为“清空”,另一个Name属性为Tjbtn,Caption属性为“统计”;再加入两个Label控件,Label1和Label2的Caption属性都为空。
在程序中中加入如下代码:
Private Sub Form_Load()'初始化
Check1.Value = 1
Text1.text = “”
End Sub
Private Sub Clearbtn_Click()
Text1.text = “” '清空文本框
End Sub
'当拖放经过文本框时
Private Sub Text1_OLEDragOver(Data As DataObject,Effect As Long,Button As Integer,Shift As Integer,X As Single,Y As Single,State As Integer)
If Data.GetFormat(vbCFText) Or Data.GetFormat(vbCFFiles) Then
Effect = vbDropEffectCopy And Effect
Exit Sub
End If
Effect = vbDropEffectNone
End Sub
'完成拖动时
Private Sub Text1_OLEDragDrop(Data As DataObject,Effect As Long,Button As Integer,Shift As Integer,X As Single,Y As Single)
If Data.GetFormat(vbCFText) Then
Text1.text = Data.GetData(vbCFText)
'当数据类型为文本时
End If
If Data.GetFormat(vbCFFiles) Then
'当数据类型为文件时
Dim vfn
For Each vfn In Data.Files
dropfile Text1, vfn
'调用子函数,在文本框中打开文件
Next vfn
End If
End Sub
'在文本框中打开文件的子函数
Sub dropfile(ByVal text As TextBox,ByVal strfn$)
Dim ifile As Integer
ifile = FreeFile
Open strfn For Input Access Read Lock Read Write As #ifile
Dim str$,strline$
While Not EOF(ifile) And Len(str) <= 32000
Line Input #ifile,strline$
If str <> “” Then str = str & vbCrLf
str = str & strline
Wend
Close #ifile
text.SelStart = Len(text)
text.SelLength = 0
text.SelText = str
End Sub
'统计按钮被按下时
Private Sub Tjbtn_Click()?煟?
Dim s As String,temp As String
Dim i As Integer,e As Integer,c As Integer
s = Text1.text
e = 0
c = 0
For i = 1 To Len(s)??
temp = Mid$(s,i,1)
If Asc(temp) >= 33 And Asc(temp) <= 126 Then
'若是英文字符
e = e + 1
ElseIf Asc(temp) < 0 Then
'若是中文字符
c = c + 1
End If
Next i
Label1.Caption = “英文字数” & CStr(e)??
Label2.Caption = “中文字数” & CStr(c)??
End Sub