Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

count a certain character in a string

Status
Not open for further replies.

tester321

Programmer
Mar 13, 2007
150
CA
Hi i have to count the underscore of many strings, i don't want to ubound an array of the split string casue of the resource intensiveness, So i kindly asking if there is a function i dont know of (cause i couldn't find one) that can do this, or can regex accomplish this as well.

the string can contain upwards of 12 underscores and have no constant format to them.

Thanks
 
I'm not sure that it would be faster than SPLIT and UBOUND, but you could strip all the ANSI codes out except underscores and count the remnant. Try both methods and time them.

Code:
response.write CountUnderscores("This_is_a_string_with_underscores")

FUNCTION CountUnderscores(input_string)
  FOR i = 0 TO 255
    IF NOT i = 95 THEN
      input_string = REPLACE(input_string,CHR(i),"")
    END IF
  NEXT
  CountUnderscores = LEN(input_string)
END FUNCTION
 
Instead of replacing all the characters in a loop, just replace the underscores with empty string. Then calculate the difference in length.

Len("This_is_a_string_with_underscores") = 33
Len("Thisisastringwithunderscores") = 28

33 - 28 = 5

So...

Code:
FUNCTION CountUnderscores(input_string)
  CountUnderscores = LEN(input_string) - Len(Replace(input_string, "_", ""))
END FUNCTION

-George

Strong and bitter words indicate a weak cause. - Fortune cookie wisdom
 
[tt]set rx=new regexp
with rx
.pattern="_"
.global=true
end with

s="string_with_many_underscores_like_this_one"
response.write "string: " & s & "<br />" & vbcrlf & _
"count '_' : " & rx.execute(s).count
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top