如何确定字符串中的所有字符是否相等 [英] How to determine if all characters in a string are equal

查看:132
本文介绍了如何确定字符串中的所有字符是否相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道字符串中的所有字符是否相等(由同一个字符组成)。该函数必须返回true或false,这取决于字符串的所有元素是否等于特定的字符。

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 are equal to an particular char.

我写了这个功能很好,但我正在看对于一个更优化(最快)的解决方案,字符串可以有数千个字符。

I wrote this function that works well, but I'm looking for a more optimal (fastest) solution, the strings can have thousands of chars.

function AllElementsAreEqual(Element:Char;Str:String):Boolean;
var
  i : Integer;
begin
Result:=True;
 if Str<>'' then
  for i:=1 to Length(Str) do
   if  Str[i]<>Element then
   begin
      Result:= False;
      exit;
   end;
end;

更新
最后使用Barry Kelly建议并添加 inline 指令,性能显着提高。

UPDATE finally using the Barry Kelly Suggestion and adding the inline directive, the performance was significantly improved.

function AllElementsAreEqual(Const Element:Char;Str:String):Boolean;inline;
type
ArrayInt = Array of Integer;
var
  i    : Integer;
  Delta: Integer;
  List : ArrayInt;
  Test : Integer;
begin
  Result:=True;
  Delta:=(Length(Str) mod  4);
  if Delta<>0 then
  Str:=Str+StringOfChar(Element,4-Delta);
  Test:=Ord(Element) + Ord(Element) shl 8 + Ord(Element) shl 16 + Ord(Element) shl 24;
  List:=ArrayInt(@(Str[1]));

  for i:=0 to ((Length(Str) div 4)-1) do
   if List[i]<>Test  then
    begin
     Result:=False;
     exit;
    end;
end;

更新2

我很抱歉,但我发布了解决方案的旧实现(有一个bug),现在已经修复了。
感谢 The_Fox ,以更好地实施Barry建议。

i'm sorry but i posted an old implementation of the solution (with a bug), now is fixed. Thanks to The_Fox for create a better implementation of the Barry suggestion.

推荐答案

您可以考虑使用元素整数 c $ c>重复4次(因为这是Delphi 7中的 AnsiChar ),像 Ord(Element)+ Ord(Element)shl 8 + Ord(Element)shl 16 + Ord(Element)shl 24 ,然后将字符串转换为 PIntegerArray ^ array [0..MaxInt div 4 - 1] of Integer )并循环它 Length(Str)div 4 times,以整数比较而不是人物。您需要手动比较最后几个 Length(str)mod 4 的字符。

You could consider creating an Integer value with the Element repeated 4 times (since this is AnsiChar in Delphi 7), shifted like Ord(Element) + Ord(Element) shl 8 + Ord(Element) shl 16 + Ord(Element) shl 24, then typecast the string to a PIntegerArray (^array[0..MaxInt div 4 - 1] of Integer) and loop over it Length(Str) div 4 times, comparing as integers instead of characters. You'll need to compare the last few Length(str) mod 4 characters manually though.

这篇关于如何确定字符串中的所有字符是否相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆