String Occurence Function

I'm having trouble thinking up a good algorithm for a function called "occurrence" that will return a byte of how many times a substring occurs in a string. I want the function as small as possible...

Can anyone help?

Comments

  • : I'm having trouble thinking up a good algorithm for a function called "occurrence" that will return a byte of how many times a substring occurs in a string. I want the function as small as possible...
    :
    : Can anyone help?
    :
    Here is a simple, untested function:
    [code]
    function Occurance(SubStr, S: string): integer;
    begin
    Result := 0;
    while Pos(SubStr, S) > 0 do { Find first occurance of SubStr in S }
    begin
    Result := Result + 1;
    Delete(S, 1, Pos(SubStr, S)+Length(SubStr)-1);
    { Delete everyting upto and including previously found SubStr }
    end;
    end;
    [/code]

  • : : I'm having trouble thinking up a good algorithm for a function called "occurrence" that will return a byte of how many times a substring occurs in a string. I want the function as small as possible...
    : :
    : : Can anyone help?
    : :
    : Here is a simple, untested function:
    : [code]
    : function Occurance(SubStr, S: string): integer;
    : begin
    : Result := 0;
    : while Pos(SubStr, S) > 0 do { Find first occurance of SubStr in S }
    : begin
    : Result := Result + 1;
    : Delete(S, 1, Pos(SubStr, S)+Length(SubStr)-1);
    : { Delete everyting upto and including previously found SubStr }
    : end;
    : end;
    : [/code]
    :


    Thanks! That's exactly what I was looking for. I thought it would be more difficult than that...

  • : : : I'm having trouble thinking up a good algorithm for a function called "occurrence" that will return a byte of how many times a substring occurs in a string. I want the function as small as possible...
    : : :
    : : : Can anyone help?
    : : :
    : : Here is a simple, untested function:
    : : [code]
    : : function Occurance(SubStr, S: string): integer;
    : : begin
    : : Result := 0;
    : : while Pos(SubStr, S) > 0 do { Find first occurance of SubStr in S }
    : : begin
    : : Result := Result + 1;
    : : Delete(S, 1, Pos(SubStr, S)+Length(SubStr)-1);
    : : { Delete everyting upto and including previously found SubStr }
    : : end;
    : : end;
    : : [/code]
    : :
    :
    :
    : Thanks! That's exactly what I was looking for. I thought it would be more difficult than that...
    :
    :
    There are other ways. You could also loop through the string and compare the substr to a part of the s using Copy(). Or you could typecast both as PChars and use a memory compare to compare the parts.
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories