问题
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?"
回答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;
回答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 }
回答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.
回答4:
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;
回答5:
function stringcount(pBefore: String; pSubstring: String; pFlags: TReplaceFlags): Integer;
begin
result:= round((pBefore.Length - stringreplace(pBefore, pSubstring, '', pFlags).Length) / pSubstring.Length);
end;
来源:https://stackoverflow.com/questions/5265317/delphi-count-number-of-times-a-string-occurs-in-another-string