With this scripting code, you can count how many words a particular string has. Two functions, namely CountWordsA and CountWordsB are provided to accomplish that. Try the one you feel most comfortable with.
Although both function may appear to be similar, the way they determine number of words in a string is slightly different. Both functions iterate, one character at a time, through the string (the parameter you pass) to count the number of words in a string. No we cannot just count space characters in a string to find out how many words we have because each string may contain more than one space character. We rather need a different approach. The first function, CountWordsA, assumes that you want to count a "word" as a "word" if the current character is a space and the next character is not. That eliminates the possibility of counting words that could be separated by more than one space character as any consecutive space characters (specifically, the current and the next space character) would not be ignored.
On the other hand, the second function, CountWordsB, compares the current and the previous characters in a string. If they both are space characters, then, it is not a word. If, however, the current character is a space character and the previous character was not, then, we know it is a word.
<%dim aStringaString = "a b c d e "response.write "Number of words returned from CountWordsA (): " & CountWordsA (aString)response.write "<br>Number of words returned from CountWordsB (): " & CountWordsB (aString)function CountWordsA (str)str = trim (str) ' remove spaces, if any, from both sides of stringdim intTotalWords, intStrLengthintStrLength = len(str) ' store the number of characters in the stringintTotalWords = 1if intStrLength = 0 then ' check if the string is emptyintTotalWords = 0 ' 0 words if the string is emptyelse ' string is not emptydim i, strCurChar, stNextCharfor i = 1 to intStrLength - 1strCurChar = mid(str, i, 1) ' current characterstNextChar = mid(str, i+1, 1) ' next characterif strCurChar = Chr(32) and stNextChar <> Chr(32) thenintTotalWords = intTotalWords + 1end ifnextend ifCountWordsA = intTotalWordsend functionfunction CountWordsB (str)str = trim (str) ' remove spaces, if any, from both sides of stringdim intTotalWords, intStrLengthintStrLength = len(str) ' store the number of characters in the stringintTotalWords = 1if intStrLength = 0 then ' check if the string is emptyintTotalWords = 0 ' 0 words if the string is emptyelse ' string is not emptydim i, strCurChar, strPrevCharfor i = 2 to intStrLengthstrCurChar = mid(str, i, 1) ' current characterstrPrevChar = mid(str, i-1, 1) ' previous characterif strCurChar = Chr(32) and strPrevChar <> Chr(32) thenintTotalWords = intTotalWords + 1end ifnextend ifCountWordsB = intTotalWordsend function%>