gpt4 book ai didi

c# - 如何检查字符串是否包含超过 50 个字符的单词?

转载 作者:太空宇宙 更新时间:2023-11-03 17:18:39 24 4
gpt4 key购买 nike

如何检查字符串是否包含超过 50 个字符的单词?

最佳答案

例如。使用 LINQ:

string toCheck = "your string here";
bool isLong = toCheck
.Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Any(s => s.Length > 50);

编辑

出于好奇,人们怀疑 Regex 会更快(我也这么认为),我运行了几个简单的测试。不得不承认我对结果感到惊讶:

LINQ(或准确地说,string.Split 和 LINQ)的执行速度似乎比已编译的 Regex 快 3-20 倍,比未编译的快 6-30 倍。

我在 Release 模式下对每个解决方案运行了 1'000'000 次迭代,检查了 4 个示例字符串:

  • 没有 50 个字符以上的长词
  • 恰好有一个 50 个字符以上的长单词,位于字符串的结尾
  • 恰好有一个 50 个字符以上的长单词,位于字符串的开头
  • 一个有多个 50 个字符以上的长词,分布在字符串中

可以在此处查看结果(LINQ 与编译的正则表达式):

LINQ [noLongWords], 1000000 iterations. Result = False: 867 ms

LINQ [oneLongWordAtEnd], 1000000 iterations. Result = True: 986 ms

LINQ [oneLongWordAtBegining], 1000000 iterations. Result = True: 827 ms

LINQ [manyLongWordsEverywhere], 1000000 iterations. Result = True: 2399 ms

Regex [noLongWords], 1000000 iterations. Result = False: 16714 ms

Regex [oneLongWordAtEnd], 1000000 iterations. Result = True: 14225 ms

Regex [oneLongWordAtBegining], 1000000 iterations. Result = True: 6483 ms

Regex [manyLongWordsEverywhere], 1000000 iterations. Result = True: 6675 ms

测试源代码可用here .

当然,在常规条件下(谁理智地运行 1'000'000 迭代?),差异是无关紧要的,应该寻求更容易/更可维护的解决方案。

关于c# - 如何检查字符串是否包含超过 50 个字符的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5760070/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com