How do I count the number of strings inside a string?
Like for this sentence:
"hello, my name is bob, and I like to bot on Runescape using simba, Simba is awesome"
How would I count the amount of "simba" in that string?
How do I count the number of strings inside a string?
Like for this sentence:
"hello, my name is bob, and I like to bot on Runescape using simba, Simba is awesome"
How would I count the amount of "simba" in that string?
Ello @Officer Barbrady!
Here you go, CountEx() from String Handling Commands:
Obviously overlap doesn't matter in this case, so you could aswell just use Count() from there.Code:function CountEx(s, str: string; overlap: Boolean): Integer; var p, o: Integer; begin Result := 0; if not overlap then begin o := Length(s); p := (p - (o - 1)); end else o := 1; if (o <= Length(str)) then repeat p := PosEx(s, str, (p + o)); if (p > 0) then Inc(Result); until (p <= 0); end; var s, str: string; begin ClearDebug; str := '"hello, my name is bob, and I like to bot on Runescape using simba, Simba is awesome"'; s := 'simba'; WriteLn('String: "' + str + '"'); WriteLn('Count of "' + s + '" in String: ' + IntToStr(CountEx(s, str, True)) + ' (case-sensitive = TRUE & overlap = ON)!'); WriteLn('Count of "' + s + '" in String: ' + IntToStr(CountEx(s, str, False)) + ' (case-sensitive = TRUE & overlap = OFF)!'); WriteLn('Count of "' + Lowercase(s) + '" in String: ' + IntToStr(CountEx(Lowercase(s), Lowercase(str), True)) + ' (case-sensitive = FALSE & overlap = ON)!'); WriteLn('Count of "' + Lowercase(s) + '" in String: ' + IntToStr(CountEx(Lowercase(s), Lowercase(str), False)) + ' (case-sensitive = FALSE & overlap = OFF)!'); end.
Like this:
Do note, that it is case-sensitive! So, if you want to match "Simba" and "simba", then you'll need to use lowercase()'s.Code:function Count(s, str: string): Integer; var p, sL: Integer; begin Result := 0; sL := Length(s); p := (p - (sL - 1)); if (sL <= Length(str)) then repeat p := PosEx(s, str, (p + sL)); if (p > 0) then Inc(Result); until (p <= 0); end; var s, str: string; begin ClearDebug; str := '"hello, my name is bob, and I like to bot on Runescape using simba, Simba is awesome"'; s := 'simba'; WriteLn('String: "' + str + '"'); WriteLn('Count of "' + s + '" in String: ' + IntToStr(Count(s, str)) + ' (case-sensitive = TRUE)!'); WriteLn('Count of "' + Lowercase(s) + '" in String: ' + IntToStr(Count(Lowercase(s), Lowercase(str))) + ' (case-sensitive = FALSE)!'); end.
Regards,
-Jani
Last edited by Janilabo; 05-24-2013 at 04:06 PM.
There are currently 1 users browsing this thread. (0 members and 1 guests)