Jon*_*nas 21 delphi string delphi-2007
我正在使用Delphi 2007,并想知道是否有一种简单的方法来计算字符串在另一个字符串中出现的次数.我可以使用任何内置函数?
例子:
And*_*and 38
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;
Run Code Online (Sandbox Code Playgroud)
Rob*_*ank 10
我见过的最聪明的方法之一:
{ 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 }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19050 次 |
| 最近记录: |