SRL Archive - OSR Help

How do I count the number of strings in a string?


rj

2013-05-24 11:08:19

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?

Janilabo

2013-05-24 11:47:44

Ello @Officer Barbrady!

Here you go, CountEx() from String Handling Commands:

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.

Obviously overlap doesn't matter in this case, so you could aswell just use Count() from there. :)

Like this:

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.

Do note, that it is case-sensitive! So, if you want to match "Simba" and "simba", then you'll need to use lowercase()'s.

Regards,
-Jani