2004. február 19., csütörtök

Get the number of occurrences of a substring within a string


Problem/Question/Abstract:

How to get the number of occurrences of a substring within a string

Answer:

Answer 1:

I don't know of any existing code in Delphi to do this. If performance isn't critical you can always use brute force. The following works but can easily be improved:

function CountSubString(SubStr, St: string): integer;
var
  i: integer;
begin
  Result := 0;
  for i := 1 to Length(st) do
    if (copy(st, i, length(SubStr)) = SubStr) then
      inc(Result);
end;


Answer 2:

While you can fiddle with the pos function and truncating the containing string after each "find," I think the brute force method is easiest to code (untested):

function SubstrCount(sub, container: string): integer;
var
  index: integer;
begin
  result := 0;
  for index := 1 to (length(container) - length(sub) + 1) do
    if copy(container, index, length(sub)) = sub then
      inc(result);
end;

If you need to skip over the found substring, say to count two occurrences of "AA" within "AAAA" instead of three, change to:

function SubstrCount(sub, container: string): integer;
var
  index: integer;
begin
  result := 0;
  index := 1;
  while index <= (length(container) - length(sub) + 1) do
  begin
    if copy(container, index, length(sub)) = sub then
    begin
      inc(result);
      index := index + length(sub);
    end
    else
      inc(index);
  end;
end;


Answer 3:

function SubStringCount(const str, substr: string): Integer;
var
  start: integer;
begin
  result := 0;
  start := 0;
  repeat
    start := posex(substr, str, start + 1);
    if (start = 0) then
      break
    else
      inc(Result);
  until
    false;
end;

Nincsenek megjegyzések:

Megjegyzés küldése