博客
关于我
Linq to object 技巧、用法集锦
阅读量:803 次
发布时间:2023-01-31

本文共 975 字,大约阅读时间需要 3 分钟。

要判断字符串数组里的元素是否在字符串中出现,可以用Contains方法逐个检查。以下展示了两种实现方法。

方法一:使用 LINQ

using System.Linq;public class Program{    static void Main(string[] args)    {        string str = "你在他乡还好吗?";        string[] WordList = new string[]        {            "他乡",            "家庭",            "还好",            "怎么"        };        int count = WordList.Count(m => str.Contains(m));        Console.WriteLine(count);        Console.ReadKey();    }}

方法二:逐个检查循环

public class Program{    static void Main(string[] args)    {        string str = "你在他乡还好吗?";        string[] WordList = new string[]        {            "他乡",            "家庭",            "还好",            "怎么"        };        int count = 0;        foreach (string word in WordList)        {            if (str.Contains(word))                count++;        }        Console.WriteLine(count);        Console.ReadKey();    }}

代码解释

两种方法都通过检查每个字符串是否包含在主字符串中来统计出现次数。

优点

  • 简洁性:LINQ代码简洁易读。
  • 性能:对于小型数据集,两种方法性能相当。

结果

编译并运行这段代码,会输出2,表示有两个数组元素出现在原字符串中。

转载地址:http://gkwfk.baihongyu.com/

你可能感兴趣的文章
Python - 如何解析 xml 响应并将元素值存储在变量中?
查看>>
Python - 安装了扩展的远程 Webdriver
查看>>
python - 将字符串中的日期与今天的日期进行比较
查看>>
python - 数据描述符(class 内置 get/set/delete方法 )
查看>>
Python - 根据值绘制彩色网格
查看>>
Python - 正则表达式在括号之间获取数字
查看>>
Python - 正则表达式在括号之间获取数字
查看>>
Python - 正则表达式在括号之间获取数字
查看>>
Python - 类 __hash__ 方法和集合
查看>>
Python - 轻松将文本文件内容转换为字典值/键
查看>>
Python - 递归和列表
查看>>
python -- 小数据池 is和 == 再谈编码
查看>>
Python -- 算法实现
查看>>
python --- 元组(tuple)
查看>>
python --- 列表(list)
查看>>
python --- 协程
查看>>
python --- 字符串 str
查看>>
python ----元组方法以及修改细节
查看>>
python ----字典dict
查看>>
python / 解决 pyinstaller 打包后运行时提示找不到模块的问题
查看>>