'Delphi: count number of times a string occurs in another string
I'm using Delphi 2007 and wonder if there is a simple way of counting the number of times a string occurs in another string. Any builtin function I can use?
Examples:
- "How" occurs once in the string "How are you?"
- "do" occurs twice in the string "How do you do?"
Solution 1:[1]
function Occurrences(const Substring, Text: string): integer;
var
offset: integer;
begin
result := 0;
offset := PosEx(Substring, Text, 1);
while offset <> 0 do
begin
inc(result);
offset := PosEx(Substring, Text, offset + length(Substring));
end;
end;
Solution 2:[2]
One of the most clever ways I've ever seen to do this:
{ Returns a count of the number of occurences of SubText in Text }
function CountOccurences( const SubText: string;
const Text: string): Integer;
begin
if (SubText = '') OR (Text = '') OR (Pos(SubText, Text) = 0) then
Result := 0
else
Result := (Length(Text) - Length(StringReplace(Text, SubText, '', [rfReplaceAll]))) div Length(subtext);
end; { CountOccurences }
Solution 3:[3]
If you find yourself frequently searching occurences in a large body of text and performance becomes an issue, you could try the Boyer-Moore search algorithm.
the worst-case to find all occurrences in a text needs approximately 3n comparisons
An implementation in Delphi can be found at our very own SO here
I need three fast-on-large-strings functions: fast search, fast search and replace, and fast count of substrings in a string.
Solution 4:[4]
function stringcount(pBefore: String; pSubstring: String; pFlags: TReplaceFlags): Integer;
begin
result:= round((pBefore.Length - stringreplace(pBefore, pSubstring, '', pFlags).Length) / pSubstring.Length);
end;
Solution 5:[5]
uses
StrUtils;
function Occurrences(const Substring, Text: string;
const ignoreUppercase: Boolean = false): Integer;
var
inSubstring, inText: string;
inPos: Integer;
begin
Result:= 0;
if (Substring = '') or (Text = '') then
Exit;
if ignoreUppercase then
begin
inSubstring:= AnsiLowerCase(Substring);
inText:= AnsiLowerCase(Text);
end
else
begin
inSubstring:= Substring;
inText:= Text;
end;
inPos:= 1;
repeat
inPos:= posEx(inSubstring, inText, inPos);
if inPos > 0 then
begin
Inc(Result);
inPos:= inPos + Length(inSubstring);
end;
until inPos = 0;
end;
Solution 6:[6]
Newer Delphi versions have a CountChar string helper, counting occurrences of a single character in a string:
var
MyText: String;
begin
MyText := 'How are you?';
ShowMessage(MyText.CountChar('o').ToString);
end;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | RobertFrank |
| Solution 3 | Community |
| Solution 4 | Johan |
| Solution 5 | |
| Solution 6 | Anse |
