GetWordCount

Counts how many words found inside a string.
Using space, tab or enter as separators.

CodeFunctionName
What is this?

Public

Not Tested

Imported
<%
'*******************************************************
'* ASP 101 Sample Code - http://www.asp101.com *
'* This code is made available as a service to our visitors and is provided strictly for the purpose of illustration. *
'* Please direct all inquiries to webmaster@asp101.com *
'*******************************************************
% >

<%
Dim strScriptName
Dim strInputText

' Read in the script name so I know where to point the form's action to.
strScriptName = Request.ServerVariables("URL")

' Read in the input from the text area.
strInputText = Request.Form("txtWordCount")

' Check for empty input and ignore it...
If strInputText = "" Then
strInputText = "This is some text for the textarea!"
Else
' Echo out the input:
Response.Write "You entered: <br / >" & vbCrLf
Response.Write " <pre >"
Response.Write Server.HTMLEncode(strInputText)
Response.Write " </pre >" & vbCrLf

' Print out the counts we got:
Response.Write " <p >It contained <b >" _
& GetWordCount(strInputText) _
& " </b > words and <b >" _
& GetCharCount(strInputText) _
& " </b > characters. </p > <br / >" & vbCrLf
End If

' I wrapped these into functions so you can reuse them.
'**** Begin Functions ***********************************
Function GetWordCount(strInput)
Dim strTemp

' Deal with tabs and carriage returns by replacing them with spaces.
strTemp = Replace(strInput, vbTab, " ")
strTemp = Replace(strTemp, vbCr, " ")
strTemp = Replace(strTemp, vbLf, " ")

' Remove leading and trailing spaces
strTemp = Trim(strTemp)

' Combine multiple spaces down to single ones
Do While InStr(1, strTemp, " ", 1) < > 0
strTemp = Replace(strTemp, " ", " ")
Loop

' Get a count by splitting the string into an array and retreiving the number of elements in it.
' I add one to deal with the 0 lower bound.
GetWordCount = UBound(Split(strTemp, " ", -1, 1)) + 1
End Function ' GetWordCount

Function GetCharCount(strInput)
GetCharCount = Len(strInputText)
End Function ' GetCharCount
'**** End Functions *************************************

' Here's our form that we fill with the value they entered last time.
% >
<p >Enter some text: </p >

<form action=" <%= strScriptName % >" method="post" >
<textarea name="txtWordCount" cols="40" rows="5" > <%= Server.HTMLEncode(strInputText) % > </textarea >
<br / >
<input type="submit" >
</form >

strInput

Provided inside post

Views 2,511

Downloads 929

CodeID
DB ID