This is a special mid-week edition of Reusable Code. While preparing this weekend's edition, I discovered that for the ASP examples we would need another utility function that is useful outside of working with Roman numerals. I feel it important enough to have it's own post, but I don't want to delay the upcoming posts.
ASP programmers are probably familiar with the Instr() function. It returns the location of one string within another. Sometimes you want to know how many times one string occurs within another. PHP programmers have a built-in function called substr_count() which can do this. We're going to write our own function in ASP to duplicate some of this functionality.
function InstrCount(haystack, needle)
if needle <> "" then
InstrCount = UBound(Split(haystack, needle))
end if
end function
It's fairly self-explanatory, but just in case you're not familiar with the Split() function... We are splitting the string into an array, using the search string (needle) as our delimiter. The upper bound of the array gives us the number of needles in our haystack.
Why didn't I call the function substr_count() to match PHP? Normally I do like to have things consistent between languages because it makes it easier for people to go from one to the other, but in this particular case, the PHP function substr_count has two optional arguments. Since ASP does not support optional arguments (at least not the way you would expect), I went with a name more similar to the complementary Instr() function.
No comments:
Post a Comment