22 delphi delphi-2010 delphi-xe2
如何计算Delphi中字符串中某个字符的出现次数?
例如,假设我有以下字符串并且想要计算其中的逗号数:
S := '1,2,3';
Run Code Online (Sandbox Code Playgroud)
然后我想获得2结果.
And*_*and 37
你可以使用这个简单的功能:
function OccurrencesOfChar(const S: string; const C: char): integer;
var
i: Integer;
begin
result := 0;
for i := 1 to Length(S) do
if S[i] = C then
inc(result);
end;
Run Code Online (Sandbox Code Playgroud)
Rob*_*ank 19
即使已经接受了答案,我也会在下面发布更通用的功能,因为我发现它非常优雅.此解决方案用于计算字符串而不是字符的出现次数.
{ Returns a count of the number of occurences of SubText in Text }
function CountOccurences( const SubText: string;
const Text: string): Integer;
begin
Result := Pos(SubText, Text);
if Result > 0 then
Result := (Length(Text) - Length(StringReplace(Text, SubText, '', [rfReplaceAll]))) div Length(subtext);
end; { CountOccurences }
Run Code Online (Sandbox Code Playgroud)
Ken*_*ite 17
而对于那些喜欢现代Delphi版本中的枚举器循环的人来说(并不比Andreas公认的解决方案更好,只是另一种解决方案):
function OccurrencesOfChar(const ContentString: string;
const CharToCount: char): integer;
var
C: Char;
begin
result := 0;
for C in ContentString do
if C = CharToCount then
Inc(result);
end;
Run Code Online (Sandbox Code Playgroud)
Rau*_*aul 10
如果你不处理大文本,这个可以做的工作
...
uses RegularExpressions;
Run Code Online (Sandbox Code Playgroud)
...
function CountChar(const s: string; const c: char): integer;
begin
Result:= TRegEx.Matches(s, c).Count
end;
Run Code Online (Sandbox Code Playgroud)