c# - 检查字符串是否包含任何字符串数组值,然后获取子字符串

标签 c# arrays string

这可能是这个 SO Question 的子问题.我想根据字符串或列表数组检查字符串。 例子

string address = "1st nice ave 1st floor";    
//For now, I'm getting the list from a text file but could move to use an EF    
List<string> streetType = File.ReadLines(AppDomain.CurrentDomain.BaseDirectory + @"streetType.csv")
                              .Where(x => x.Length > 0)
                              .Select(y => y.ToLowerInvariant())
                              .ToArray();

目的是去除大道后的额外地址详细信息,csv 文件包含所有 USPS 接受的街道类型。

这是我现在拥有的

//this only returns boolean value, I got this from the SO above
streetType.Any(testaddress.ToLower().Contains);

//I also have this
Array.Exists<string>(streetType, (Predicate<string>)delegate (string s)
{         
   return testaddress.IndexOf(s, StringComparison.OrdinalIgnoreCase) > -1;       
});

我一直在寻找如何解决这个问题,然后我遇到了 SO 问题,这正是我想要的,但我需要获取子字符串以进行剥离。

如果有 linq 查询,那就太棒了。我能想到的唯一方法是使用 foreach 和 inner if。

数组值的例子

  • 大道
  • 公共(public)汽车

更新:

这是我的答案,我忘了提到数组查找需要匹配地址字符串中的确切字符串。我最终使用了正则表达式。这是@giladGreen 的扩展/修改答案。

  var result = from item in streetTypes
                         let index = Regex.Match(address.ToLowerInvariant(), @"\b" + item.ToLowerInvariant() + @"\b")
                         where index.Success == true
                         select address.ToLowerInvariant().Substring(0, index.Index + item.Length);

有人可以将其转换为 lambda 表达式吗?我试过但失败了。

谢谢大家

最佳答案

使用 IndexOf 了解项目是否存在于 address 中,如果是,则返回其后的字符串:

var result = from item in streetType
             let index = address.IndexOf(item)
             where index != -1
             select address.SubString(0, index);

关于c# - 检查字符串是否包含任何字符串数组值,然后获取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52317762/

相关文章:

javascript - 纯 JavaScript |将类添加到 <li> 元素

python - 从 C 调用 Python 函数并使用 C 中的 2D Numpy 数组

javascript - 在 Javascript 中交换数组元素

c++ - Printf 和 C++ 字符串

ios - 从 NSString 转换为 Swift String 时文本被截断

c# - 使用 GetSaveFileName 创建 SaveFileDialog 时如何停止覆盖提示

c# - 从 DLL 动态加载 WPF View 和 View 模型

c# - “Illegal characters in path.” 仅当从移动浏览器查看时

C++:从字符串流到字符**

c# - 如何使 UpdateTargetId 在 Ajax.ActionLink 中工作?