在 Visual Basic 中计算单词数
我正在尝试实现一个程序,在您键入时计算多行文本框中的单词数。我可以让它计算单词,直到我按下“输入”键并输入一个单词。它不认识这一点。这是我的代码:
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles TextBox1.TextChanged
Dim str As String
Dim i, l, words As Integer
str = TextBox1.Text
str = LTrim(str) 'removes blank spaces at the beginning of text
str = RTrim(str) ' removes blank spaces at the end of text
l = str.Length
i = 0
words = 0
While (i < l)
If str(i) = " " Then
words = words + 1
i = i + 1
While str(i) = " " ' removes more than 1 blank space
i = i + 1
End While
Else
i = i + 1
End If
End While
words = words + 1 ' adds the last word
TextBox2.Text = ("" & words)
End Sub
I am trying to implement a programme that counts the words in a multiline textbox as you type. I can get it counting the words until I press the "enter" key and type a word. It does not recognise this. This is my code:
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles TextBox1.TextChanged
Dim str As String
Dim i, l, words As Integer
str = TextBox1.Text
str = LTrim(str) 'removes blank spaces at the beginning of text
str = RTrim(str) ' removes blank spaces at the end of text
l = str.Length
i = 0
words = 0
While (i < l)
If str(i) = " " Then
words = words + 1
i = i + 1
While str(i) = " " ' removes more than 1 blank space
i = i + 1
End While
Else
i = i + 1
End If
End While
words = words + 1 ' adds the last word
TextBox2.Text = ("" & words)
End Sub
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
这是另一个正则表达式解决方案:
Here's another regex solution:
为什么不改成正则表达式,整个事情可以像这样
Why not change to regex that whole thing can be like this
您需要删除“返回”键
添加这些行:
之前
You need to remove the "return" key
Add these lines:
before
这是我计算单词数的方法
this is my way of counting words
不要使用
更好的
Don't use
Better
如果您想在不使用正则表达式的情况下进行简单的字数统计,
在这种情况下 iWords 值将为 3(无需使用修剪或替换)
If you would like an easy word count without using Regex
iWords value will be 3 in this case (no need to use trim or replaces)
我见过很多例子,人们计算空白并认为这些相当于计算单词数。那么这是不正确的,您不应该使用此方法。我能想到在几种情况下这不起作用:
现在这就是我的想法。在现有字符串的开头添加一个空格。然后用空格字符替换所有出现的换行符。然后从字符串的开头开始逐个检查字符,如果当前字符是空格而后面的字符不是,那么你就得到了一个单词。就这么简单!适用于连续空格、换行符以及几乎任何我可以使用的内容。
VB6中的实现:
I have seen a lot of examples where people count empty spaces and think these are equivalent to the count of words. Well this is not correct and you should not use this method. There are several cases I can think of where this does not work:
Now here is what I have come up with. Add an empty space to the beginning of an existing string. Then replace all newline occurrences with empty space characters. Then check one by one the characters from the start of the string, if the current character is an empty space and character following it is not, then you got a word. Simple as that! Works with consecutive spaces, newline characters and pretty much anything I could throw at it.
Implementation in VB6: