How to get a count of a given char in a string

What is the quickest way to get a count of a given character in a word? I need to make sure that no more than 1 of a given character is in each word being evaulated.

Thanks in advance,
Brad Bumgarner, CTA

set theword to “word1”
count characters of theword

set chars to characters of theword as list
offset of “o” in theword
→ 2

Thanks for your reply, however, that won’t tell me how many occurances of the letter “o” (in this case) are contained in the word, e.g. instead of “word1” if “wordone” was used, there would be 2 occurances of the letter “o” which won’t work for my purposes.

Thanks again,
Brad Bumgarner, CTA

Use the letter you are looking for as the text item delimiters and then count the number of items in the list that you get when coercing the string to a list. A count of two would indicate the requested letter only appears once in the string.

:smiley: I KNEW there was an easy way to do it. I even thought about using text item delimiters (apparently not long enough).

Thanks again,
Brad Bumgarner, CTA

Here is what i came up with

set theword to “wordone”
count characters of theword

set chars to characters of theword as list

set old_delims to AppleScript’s text item delimiters
set AppleScript’s text item delimiters to “o”
set thelist to the text items of theword
set thecount to count thelist
if thecount is greater than 2 then
display dialog “the count is greater than 2” –do something
else if thecount is equal to 2 then
do something else
display dialog “the count is 2”
end if
set AppleScript’s text item delimiters to old_delims
> 2

this script was automatically tagged for
color coded syntax by Script to Markup Code
written by Jonathan Nathan

Hi :slight_smile:
Here my small contribution (Source: http://wirinum.free.fr/vanilla/CountItem.html):

my CountItem("Hello everybody", "e") --> 3

on CountItem(txt, Itm)
	set text item delimiters of AppleScript to Itm
	set Nbr to (count (text items of txt)) - 1
	set text item delimiters of AppleScript to ""
	return Nbr
end CountItem

:wink:

Thanks go out to everyone that replied!

From the examples supplied I have been able to make my code work the way I need it :smiley:

Brad Bumgarner, CTA