String 我需要使用VBScript查找字符串中3、4、5和6个字母单词的数量

String 我需要使用VBScript查找字符串中3、4、5和6个字母单词的数量,string,vbscript,String,Vbscript,以下是我的作业必须回答的问题: 计算字符串“tx_val”中包含3、4、5或6个chatacter的字数。在span块中以逗号分隔的单行上显示这四个计数id=“ans12” 这是我的想法,输出是不正确的,我不知道为什么。我将在下面发布。我想我会告诉你们我的最新情况 threematch = 0 fourmatch = 0 fivematch = 0 sixmatch = 0 totalmatch = "" cntArr = Array() cntArr = Split(tx_val," ")

以下是我的作业必须回答的问题:

计算字符串“tx_val”中包含3、4、5或6个chatacter的字数。在span块中以逗号分隔的单行上显示这四个计数
id=“ans12”

这是我的想法,输出是不正确的,我不知道为什么。我将在下面发布。我想我会告诉你们我的最新情况

threematch = 0
fourmatch = 0
fivematch = 0
sixmatch = 0
totalmatch = ""

cntArr = Array()
cntArr = Split(tx_val," ")
i=0

For i=0 To Ubound(cntArr) Step 1
If len(cstr(cntArr(i))) = 3 Then
    threecount = threecount + 1
ElseIf len(cstr(cntArr(i))) = 4 Then
    fourcount = fourcount + 1
ElseIf len(cstr(cntArr(i))) = 5 Then
    fivecount = fivecount + 1
ElseIf len(cstr(cntArr(i))) = 6 Then
    sixcount = sixcount + 1
End If
i=i+1

Next 

totalmatch = (threecount & ", " & fourcount & ", " & fivecount & ", " & sixcount & ".")

document.getElementById("ans12").innerHTML = totalmatch
解决问题:

1) 将所有单词(以空格分隔)提取到列表中

2) 迭代列表,检查哪些单词具有指定数量的字符,每次看到匹配的单词长度时,递增一个计数器


3) 写出总计数

如果你喜欢在JavaScript中使用正则表达式,为什么不在VBScript中使用它们呢?它们都使用相同的ECMA-262,因此两种语言之间的模式是相同的。VBScript的RegExp对象可以执行与示例相同的操作

Set re = New RegExp
re.IgnoreCase = True     ' equivalent to /i modifier
re.Global = True         ' equivalent to /g modifier
re.Pattern = "\b\w{3}\b" ' regex pattern without delimiters or modifiers
Set colMatches = re.Execute(someStringOfWords)
intCount = colMatches.Count

要了解有关VBScript中正则表达式的更多信息,请访问MSDN并阅读。

首先,这就是导致错误行为的原因,您正在显式增加计数器
i
,即使下一个
循环的
已经为您这样做了。结果是,对于通过循环的每个过程,
i
实际上都会增加2

删除
i=i+1
行,脚本将按预期工作


其次,变量名不一致,初始化为
threematch
,之后用作
threecount
。您应该始终显式地声明变量(
Dim
语句),并在代码顶部写入
Option Explicit
,以便在编译时捕获这些明显的错误。纯属偶然,在您的特殊情况下,此错误实际上不会导致任何错误

我已经在我的代码中这样做了,但是我认为我得到了错误的计数。我得到的输出是2,1,1,它应该是3,4,2,1。