How to determine if all characters in a string are equal

后端 未结 6 975
甜味超标
甜味超标 2021-01-13 12:09

I need to know if all characters in a string are equal (formed by the same character). the function must return true or false depending if all the elements of the string ar

6条回答
  •  无人共我
    2021-01-13 12:21

    You implemented the suggestion of Barry Kelly wrong. When I test it on Delphi 7, it is even slower than your first implementation and it gives wrong results if your stringlength is not divisible by 4.

    I tested it with this string: StringOfChar('c', 100000) + 'x'; and your new function returns True AllElementsAreEqual('c', StringOfChar('c', 100000) + 'x') while it should return False.

    Your implementation is slower because you are trying to make your string divisable by four (in which you fail, but you can figure out by yourself why it fails) and thus creating a new string which needs memory allocations which are costly.

    Another dangerous thing you do is letting a dynamic array (array of integer) point to a string. Both are refcounted and this can lead to strange results. Please follow Barry Kelly's advise and use a PIntegerArray!

    I think Barry Kelly meant this:

    function AllElementsAreEqual(const aElement: Char; const aStr: string): Boolean;
    var
      lIntArray: PIntegerArray;
      i: Integer;
      lTest: Integer;
    begin
      Result := True;
      lTest := Ord(aElement) + Ord(aElement) shl 8 + Ord(aElement) shl 16 + Ord(aElement) shl 24;
    
      lIntArray := @aStr[1];
      for i := 0 to Length(aStr) div 4 - 1 do
        if lIntArray[i] <> lTest then
        begin
          Result := False;
          Exit;
        end;
    
      for i := Length(aStr) - (Length(aStr) mod 4) + 1 to Length(aStr) do
        if aStr[i] <> aElement then
        begin
          Result := False;
          Exit;
        end;
    end;
    

    NB: Your function returns True for empty strings, is that OK?

    NB2: Please award points to Barry Kelly's answer and not mine, because this is really an oversized comment and not an answer.

提交回复
热议问题