开发者

I need to find the number of 3, 4, 5 and 6 letter words in a string using VBScript

Here's the question I have to answer for my assignment:

Count the number of words in the string "tx_val" that have 3,4,5 or 6 chatacters. Show these four counts on a single line seperated by commas in the span block id="ans12".

Here's what I've come up with, the output is incorrect and I'm not sure why. I'll post below. Thought I'd give you all a update of where I was at with it.

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(cntAr开发者_Python百科r(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


First, and this is what is causing the wrong behaviour, you are explicitly incrementing your counter i, even though the For-Next loop already does that for you. The result is that for each pass through the loop, i actually gets incremented by 2.

Remove the i=i+1 line and your script will work as intended.

Second, your variable names are inconsistent, being initialised as e.g. threematch and later used as threecount. You should always declare your variables explicitly (Dim statements) and write Option Explicit at the top of your code to catch such obvious mistakes at compile time. By pure chance this mistake does not actually cause any errors in your particular case.


If you are comfortable using regular expressions in JavaScript, why not use them in VBScript? They both use the same ECMA-262 so patterns are identical between the two languages. VBScript's RegExp object can do the same thing as your example.

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

To learn more about Regular Expressions in VBScript, stop by the MSDN and read Microsoft Beefs Up VBScript with Regular Expressions.


Break the problem up:

1) Extract all words (break on whitespace) into a list

2) Iterate over the list, checking which words have the specified number of characters, increment a counter each time a matching word length is seen.

3) Write out the total counts

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜