Joshy
Code: Select all
' count how often the string "search" is in string "source"
function CountInString overload (byref source as string, _
byref search as string, _
byval case_sensitive as boolean=true) as integer
var sPos=0,count=0,nSource=len(source), nSearch=len(search)
if nSearch<1 then return 0
if nSource<nSearch then return 0
while sPos+nSearch <= nSource
var nSame=0,sStart=sPos
if case_sensitive then
for i as integer=0 to nSearch-1
if source[sStart]<>search[i] then exit for
sStart+=1:nSame+=1
next
else
for i as integer=0 to nSearch-1
var a=source[sStart],b=search[i]
if a>64 andalso a<91 andalso b>96 andalso b<123 then
' if a in range of "A"-"Z" and b in range "a"-"z"
b-=32 ' change b
elseif b>64 andalso b<91 andalso a>96 andalso a<123 then
' if a in range of "a"-"z" and b in range "A"-"Z"
a-=32 ' change a
end if
if a<>b then exit for
sStart+=1:nSame+=1
next
end if
if nSame=nSearch then
count+=1 : sPos+=nSearch
else
sPos+=1
end if
wend
return count
end function
' does the same but returns a redimed array of the positions
function CountInString(byref source as string, _
byref search as string, _
positions() as integer, _
byval case_sensitive as boolean=true) as integer
var sPos=0,count=0,nSource=len(source), nSearch=len(search)
if nSearch<1 then return 0
if nSource<nSearch then return 0
while sPos+nSearch <= nSource
var nSame=0,sStart=sPos
if case_sensitive then
for i as integer=0 to nSearch-1
if source[sStart]<>search[i] then exit for
sStart+=1:nSame+=1
next
else
for i as integer=0 to nSearch-1
var a=source[sStart],b=search[i]
if a>64 andalso a<91 andalso b>96 andalso b<123 then
' if a in range of "A"-"Z" and b in range "a"-"z"
b-=32 ' change b
elseif b>64 andalso b<91 andalso a>96 andalso a<123 then
' if a in range of "a"-"z" and b in range "A"-"Z"
a-=32 ' change a
end if
if a<>b then exit for
sStart+=1:nSame+=1
next
end if
if nSame=nSearch then
if ubound(positions)<count then redim preserve positions(iif(count=0,0,count shl 1))
positions(count)=sPos+1 : count+=1 : sPos+=nSearch
else
sPos+=1
end if
wend
return count
end function
var test = "az Az aZ"
print test
print "aZ",CountInString(test,"aZ")
print "Az",CountInString(test,"Az")
print "aZ",CountInString(test,"aZ")
print "AZ",CountInString(test,"AZ")
print "AZ",CountInString(test,"AZ",false)
print
redim as integer p()
test = "print Print PRINT PrInT"
print test
var count = CountInString(test,"print",p())
print "print " & count : if count then for i as integer=0 to count-1 : print p(i), : next : print
count = CountInString(test,"PRINT",p(),false)
print "PRINT " & count : if count then for i as integer=0 to count-1 : print p(i), : next : print
print
sleep