如何在 C# 中检查字符串数组是否包含特定单词?


C# 中,String.Contains() 是一个字符串方法。此方法用于检查子字符串是否出现在给定字符串中。

它返回布尔值。如果子字符串存在于字符串中或值为空字符串(""),则返回 True,否则返回 False。

异常 - 如果 str 为 null,则此方法可能会引发 ArgumentNullException。

此方法执行区分大小写的检查。搜索将始终从字符串的第一个字符位置开始,并继续到最后一个字符位置。

示例 1

如果找到字符串,Contains 区分大小写,则返回 true,否则返回 false

static void Main(string[] args){
   string[] strs = { "Sachin", "India", "Bangalore", "Karnataka", "Delhi" };
   if (strs.Contains("sachin")){
      System.Console.WriteLine("String Present");
   } else {
      System.Console.WriteLine("String Not Present");
   }
   Console.ReadLine();
}

输出

String Not Present

示例 2

static void Main(string[] args){
   string[] strs = { "Sachin", "India", "Bangalore", "Karnataka", "Delhi" };
   if (strs.Contains("Sachin")){
      System.Console.WriteLine("String Present");
   } else {
      System.Console.WriteLine("String Not Present");
   }
   Console.ReadLine();
}

输出

String Present

示例 3

static void Main(string[] args){
   string[] strs = { "Sachin", "India", "Bangalore", "Karnataka", "Delhi" };
   var res = strs.Where(x => x == "Sachin").FirstOrDefault();
   System.Console.WriteLine(res);
   Console.ReadLine();
}

输出

Sachin

示例 4

static void Main(string[] args){
   string[] strs = { "Sachin", "India", "Bangalore", "Karnataka", "Delhi" };
   foreach (var item in strs){
      if (item == "Sachin"){
         System.Console.WriteLine("String is present");
      }
   }
   Console.ReadLine();
}

输出

String is present

更新于: 2023 年 10 月 4 日

30K+ 浏览量

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.