如何在vb中显示字数的长度?

时间:2015-04-06 23:38:12

标签: vb6

所以我一直在努力弄清楚如何在vb中显示字数的长度。 例如,如果我在富文本框中键入一个句子并单击一个按钮,我想要一个表单,显示该单句中单个单词,两个字母单词,三个字母单词等的数量。当然,特定长度的单词数将以标签输出。

我在网上发现了这个短代码,用于字数统计:

dim wordcount as integer

dim a as string() = RichText.Text.Split(" ")

wordcount = a.length

但是,我不确定这段代码是否可用于获取字数的长度。关于如何在标签中输出特定长度的单词数量的任何想法?谢谢。

2 个答案:

答案 0 :(得分:0)

如下:

Private Sub mnuCount_Click()
    Const DELIMITERS As String = vbNewLine & " !"",.:;?"
    Dim WordCounts(1 To 100) As Long
    Dim Msg As String
    Dim I As Integer
    Dim WordCount As Long

    With RTB
        .Visible = False
        .SelStart = 0
        Do
            .UpTo DELIMITERS, vNegate:=True
            .Span DELIMITERS, vNegate:=True
            If .SelLength > 0 Then
                WordCounts(.SelLength) = WordCounts(.SelLength) + 1
                .SelStart = .SelStart + .SelLength
            Else
                Exit Do
            End If
        Loop
        .SelStart = 0
        .Visible = True
    End With

    Msg = "Length" & vbTab & "Count"
    For I = 1 To 100
        If WordCounts(I) > 0 Then
            Msg = Msg & vbNewLine _
                & CStr(I) & vbTab & CStr(WordCounts(I))
            WordCount = WordCount + WordCounts(I)
        End If
    Next
    Msg = Msg & vbNewLine _
        & "Grand total:" & vbNewLine _
        & vbTab & CStr(WordCount)
    MsgBox Msg
End Sub

答案 1 :(得分:0)

Pradnya的代码,翻译成VB6:

Option Explicit

Private Sub Command1_Click()
Dim str As String
Dim splitStr() As String
Dim i As Integer

str = "ABC DEF GHIJ KLMNOPQ"
splitStr = Split(str, " ")
MsgBox "Number of words = " & UBound(splitStr) + 1 & vbCrLf & _
       "Average Length = " & Len(Replace(str, " ", "")) / (UBound(splitStr) + 1)
End Sub

我也进行了一些简化。没有必要通过循环来获得平均值。要获得整体长度所需要做的就是删除空格并除以数组中元素的数量。

但是,如果要计算每个长度的单词数,则必须循环遍历数组,获取每个单词的长度并逐个存储这些值。最好的方法是设置对scrrun.dll(Windows Scripting Runtime)的引用,并使用Dictionary对象存储值。