C# (.NET) 中是否有相应比较字符串长度的函数?

发布于 2024-07-15 22:15:45 字数 474 浏览 2 评论 0原文

抱歉,不知道长度是在构造时计算的!

我得到了 200 个字符长的字符串 A,5 个字符长的字符串 B 如果我这样做

 int Al = A.length;
 int Bl = B.length;

并比较它——一切看起来都很好,但是如果我这样做几百万次 计算一下,对于我需要的东西来说太贵了。

更简单、更简洁的方法是使用一些函数来比较两个字符串,并告诉我另一个字符串何时至少与另一个字符串相同。 类似于 (compare_string_lengths(stringA,stringB) -> 其中字符串 B 必须至少与字符串 A 一样长(字符)才能为函数返回 TRUE。

是的, 我知道该函数不知道哪个字符串更短,但是如果两个字符串的长度并行计算,那么当一个字符串超过另一个字符串时,函数就知道要“回答”什么。

感谢您的任何提示。

I'm sorry, didn't know that Length is computed at construction time!!

I got 200 char long string A, 5 char long string B
If I do

 int Al = A.length;
 int Bl = B.length;

and compare it -- all seems fine BUT If I do this few million times to
calculate something, it's too expensive for the thing I need.

Much simpler and neater way would be some function that can compare two strings and tell me when the other is AT LEAST same as the other.
Something like (compare_string_lengths(stringA,stringB) -> where string B must be at least as long (chars) as string A to return TRUE for function.

Yes,
I know that the function wouldn't have any idea which string is shorter, but if lengths of the two strings would be counted in parallel so when one exceeds the other, function knows what to "answer".

Thanks for any hints.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

戈亓 2024-07-22 22:15:45

如果您只需要知道字符串的长度是否不同(或者如果您希望在比较之前检查长度是否相等),我认为您不会比比较 Length 属性更快。 从字符串中检索长度是一个 O(1) 操作。

要实际比较字符串,您需要查看每个字符,这使其成为 O(n) 操作。

编辑:

如果事情运行得太慢,您应该尝试查看分析器,最慢的部分是什么? 也许是你的琴弦的构造需要时间?

If you only need to know whether the strings differs in length (or if you wish to check whether the lenghts are equal before comparing), I don't think that you can do it faster than comparing the Length property. Retrieving the length from a string is an O(1) operation.

To actually compare the strings you need to look at each character, which makes it an O(n) operation.

Edit:

If things runs too slowly, you should try to have a look in a profiler, what is the slowest parts ? Perhaps it is the construction of your strings that takes the time ?

我是男神闪亮亮 2024-07-22 22:15:45

没有什么比比较两个字符串的长度更便宜的了。

如果您想在字符串列表中查找字符串,请使用哈希表,例如:

    var x = new System.Collections.Generic.Dictionary<string, bool>();
    x.Add("string", true);
    if (x.ContainsKey("string"))
        Console.WriteLine("Found string.");

这非常快。

There are few things cheaper than comparing the length of two strings.

If you want to find a string in a list of strings, use a Hashtable, like:

    var x = new System.Collections.Generic.Dictionary<string, bool>();
    x.Add("string", true);
    if (x.ContainsKey("string"))
        Console.WriteLine("Found string.");

This is amazingly fast.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文