gpt4 book ai didi

c# - 如何在 C# 中比较字符串和字符串数组?

转载 作者:太空狗 更新时间:2023-10-29 22:18:49 24 4
gpt4 key购买 nike

我有一个字符串;

String uA = "Mozilla/5.0 (iPad; CPU OS 8_2 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12D508 Twitter for iPhone";

String[] a= {"iphone","ipad","ipod"};

它必须返回 ipad 因为 ipad 是在第一个匹配 ipad 处的字符串。其他情况

String uA = "Mozilla/5.0 (iPhone/iPad; CPU OS 8_2 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12D508";

相同的字符串数组首先匹配到iPhone

最佳答案

所以你想要数组中最早出现在目标字符串中的单词?听起来你可能想要这样的东西:

return array.Select(word => new { word, index = target.IndexOf(word) })
.Where(pair => pair.index != -1)
.OrderBy(pair => pair.index)
.Select(pair => pair.word)
.FirstOrDefault();

详细步骤:

  • 将单词投影到一系列单词/索引对中,其中索引是该单词在目标字符串中的索引
  • 通过删除索引为 -1 的对来省略目标字符串中未出现的单词(如果未找到,string.IndexOf 返回 -1)
  • 按索引排序,使最早的单词出现在第一对
  • 选择每对中的单词,因为我们不再关心索引
  • 返回第一个单词,如果序列为空则返回null

关于c# - 如何在 C# 中比较字符串和字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30263400/

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