Jump to content
Sign in to follow this  

Simple Function to see how many times a value exists in a string

Recommended Posts

Came across an issue where I needed to see how many times a value appeared in a string. I could not find anything pre-written for this, so I wrote a simple function to count how many times a sub string appears in a string. Hope someone finds this useful.

#include <Array.au3>

$STRING_TO_CHECK = "You are the sunshine of my life. Sunshine is needed for plants to grow."

$STRING_TO_LOOK_FOR = "sunshine"







$HOW_MANY = UBound(StringSplit(StringUpper($STR_TO_SEARCH), StringUpper($STR_WANT_TO_FIND), 1))


Return $HOW_MANY -2


Hero's Dawn, an RPG Adventure completely coded in AutoITwmifunctions UDF, WMI UDF

Share this post

Link to post
Share on other sites


; RegExp String occurrences

Global $s = "Hello World, I will count letters or Numbers like 1,2,3. And so on. 111!"

MsgBox(0, "", _stringCount($s, "z"))
MsgBox(0, "", _stringCount($s, "1"))
MsgBox(0, "", _stringCount($s, "num", 1)) ; Case-insensitivity flag.

Func _stringCount($string, $toFind, $case = "(?-i)", $startPosition = 0)
    If $case = 1 Then $case = "(?i)"
    Local $count = StringRegExp($string, $case & $toFind, 3, $startPosition)
    Switch @error
        Case 0
            If IsArray($count) Then Return UBound($count)
        Case 1
            If Not IsArray($count) Then Return 0
        Case 2
            Return -1
EndFunc   ;==>_stringCount

Func StringOccurrences($data, $str, $case, $c = 1)
    While StringInStr($data, $str, 0, $c)
        $c += 1
    Return $c
EndFunc   ;==>StringOccurrences

So long,


Scripts & functions Organize Includes Let Scite organize the include files

Yahtzee The game "Yahtzee" (Kniffel, DiceLion)

LoginWrapper Secure scripts by adding a query (authentication)

_RunOnlyOnThis UDF Make sure that a script can only be executed on ... (Windows / HD / ...)

Internet-Café Server/Client Application Open CD, Start Browser, Lock remote client, etc.

MultipleFuncsWithOneHotkey Start different funcs by hitting one hotkey different times

Share this post

Link to post
Share on other sites

The example in the help file does look simpler :whistle:

$text = StringReplace("this is a line of text", " ", " ")
$numreplacements = @extended
MsgBox(0, "New string is", $text)
MsgBox(0, "The number of replacements done was", $numreplacements)

Firefox's secret is the same as Jessica Simpson's: its effortless, glamorous style is the result of — shhh — extensions!

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Create New...