如何确定字符串中的所有字符是否相等

编程入门 行业动态 更新时间:2024-10-27 20:24:38
本文介绍了如何确定字符串中的所有字符是否相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要知道字符串中的所有字符是否相等(由同一个字符组成)。该函数必须返回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.

推荐答案

您可以考虑使用元素重复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.

更多推荐

如何确定字符串中的所有字符是否相等

本文发布于:2023-10-29 20:38:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1540688.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   字符

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!