博客
关于我
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 anaconda 安装使用
查看>>
python and或or 当参数传递的时候的用法
查看>>
Python append() 与列表上的 + 运算符,为什么这些会给出不同的结果?
查看>>
Python APP自动化测试工具adb与Monkey使用详解
查看>>
Python APP自动化测试框架Appium详解
查看>>
Python APP自动化测试框架开发实战
查看>>
python argparse模块
查看>>
Python asyncio库的学习和使用
查看>>
Python AttributeError:“dict“对象没有属性“append“
查看>>
Python base64和hashlib模块
查看>>
python basic programs
查看>>
python bert_gen.py 报错Unable to load weights from pytorch checkpoint file for......
查看>>
python binascii.Error: Incorrect padding
查看>>
Python bool() 函数能否为无效参数引发异常?
查看>>
Python C 程序子进程在“for line in iter“处挂起
查看>>
Python Celery:自动化测试平台定时任务必备的三方库
查看>>
python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令
查看>>
Python CONNECT 4 CHECK WIN函数
查看>>
python cos,Python cos(90)和cos(270)不是0
查看>>
python进阶(4):Python 脚本文件重启自身进程
查看>>