TheCarver
TheCarver

Reputation: 19713

Count how many specific characters in string

I have a search box.

My admin user might search for "@MG @EB dorchester".

In ASP, I need to count how many times the symbol "@" appears in the string. How is the possible?

Upvotes: 22

Views: 52609

Answers (6)

Function FnMatchedStringCountFromText(strText,strStringToSearch)
 strLength =  Len(strText)
 strNumber = 1
 IntCount = 0
 For i = 1 to strLength
     If Instr(1,strText,strStringToSearch,0) > 0 Then
        stMatch = Instr(1,strText,strStringToSearch,0)
        strText = Mid(strText,stMatch+2,strLength)
        IntCount = IntCount+1
     Else
         Exit For
     End If
 Next
FnMatchedStringCountFromText = IntCount
End Function

Upvotes: 0

srawn
srawn

Reputation: 111

Response.write ubound(split(str,"@"))

is enough for counting the occurance of a specific character

Upvotes: 11

narayanan
narayanan

Reputation: 1

Replace the search with blank and find the difference between and original and new string will the number of time a string is present

Dim a = "I @ am @ Thirs@ty" 
Dim count 
count = Len(a) - Len(Replace(a,"@",""))
Response.write count

Upvotes: 0

AnthonyWJones
AnthonyWJones

Reputation: 189457

For JW01

Dim pos : pos = 0
Dim count : count = -1
Do 
  count = count + 1
  pos = InStr(pos + 1, str, "@")
Loop While (pos > 0)

Upvotes: 4

JW8
JW8

Reputation: 1506

Try a while loop:

Do While (str.indexOf("@") != -1)
  count = count + 1
  str = right(str, len(str) - str.indexOf("@"))
Loop

EDIT:

This for loop might make more sense:

dim strLen, curChar, count
count = 0
int strLen = len(str)
for i = 1 to strLen
  curChar = mid(str, i, 1)
  if curChar = "@"
    count = count + 1
  end if
next

Upvotes: 2

Andrew Hare
Andrew Hare

Reputation: 351496

Try this:

len(yourString) - len(replace(yourString, "@", ""))

Upvotes: 44

Related Questions