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 TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I count the number of times a character appears in a string

File and Data Processing

How do I count the number of times a character appears in a string

by  markdmac  Posted    (Edited  )
markdmac's Enterprise Ready Login Scripts

By Mark D. MacLachlan, The Spiders Parlor
http://www.thespidersparlor.com


Counting the number of times a character appears in a string can be a simple operation. It only requires a single line of code.

Code:
CharacterCount = Len(MyString) - Len(Replace(MyString, TargetCharacter, ""))

But how does it work?

OK, let's break this command down to get a good understanding of what this is doing.

We will be storing our answer in a variable called [blue]CharacterCount[/blue].
Code:
[blue]CharacterCount[/blue] = Len(MyString) - Len(Replace(MyString, TargetCharacter, ""))

Next we determine the length of our text string using [blue]Len(MyString)[/blue].
Code:
CharacterCount = [blue]Len(MyString)[/blue] - Len(Replace(MyString, TargetCharacter, ""))

Once we have the current length of our string we will next use the Replace function to replace all of the instances of our target character we want to count, we will replace it with a null. This is done with [blue](Replace(MyString, TargetCharacter, "")[/blue].
Code:
CharacterCount = Len(MyString) - Len([blue]Replace(MyString, TargetCharacter, "")[/blue])

So we have just removed all of the target characters which has shortened our string. We then check the length of that new string using the [blue]Len[/blue] function.
Code:
CharacterCount = Len(MyString) - [blue]Len([/blue]Replace(MyString, TargetCharacter, "")[blue])[/blue]

So at this point we have the length of the string from the start and the length of the string after removing our target characters. If we [blue]subtract[/blue] the latter from the former we can see how many characters were removed which tells us how many times the target character was in the string.
Code:
CharacterCount = Len(MyString) [blue]-[/blue] Len(Replace(MyString, TargetCharacter, ""))

How About A Sample

The below example counts the number of commas in the string.
[code sample]sample="this, that, other, thing, too"
CharacterCount = Len(Sample) - Len(Replace(Sample, ",", ""))
WScript.Echo CharacterCount[/code]
[code Output]4[/code]

Happy scripting.

Mark
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top