本文共 975 字,大约阅读时间需要 3 分钟。
要判断字符串数组里的元素是否在字符串中出现,可以用Contains
方法逐个检查。以下展示了两种实现方法。
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(); }}
两种方法都通过检查每个字符串是否包含在主字符串中来统计出现次数。
编译并运行这段代码,会输出2
,表示有两个数组元素出现在原字符串中。
转载地址:http://gkwfk.baihongyu.com/