C# String.Contains()方法: 检查字符串是否包含指定的子字符串

  • Post category:C#

C# String.Contains() 方法

String.Contains() 方法在 C# 中用于判断字符串是否包含指定的字符序列。该方法会返回一个布尔值,如果字符串中包含指定的字符序列,则返回 true,否则返回 false

这个方法有两个重载:

public bool Contains(string value);
public bool Contains(string value, StringComparison comparisonType);

其中第二个重载可以指定比较字符串时的方式。下面我们详细讲解这两个重载的使用方法。

String.Contains(string value)

该方法接收一个字符串参数 value,表示需要查找的字符序列。如果字符串中包含了该字符序列,则返回 true,否则返回 false

下面是一个简单的例子:

string str = "hello world";
bool result = str.Contains("world");
Console.WriteLine(result); // 输出 true

在上面的代码中,我们创建了一个字符串 str,然后使用 Contains() 方法判断该字符串是否包含字符串 world,最后输出判断结果。

下面再举一个例子:

string str = "hello world";
bool result = str.Contains("WORLD"); // 注意:此处字符串是大写的
Console.WriteLine(result); // 输出 false

在上面的代码中,虽然我们将查找的字符串改成了全大写的 WORLD,但由于 Contains() 方法是区分大小写的,所以最终结果为 false

String.Contains(string value, StringComparison comparisonType)

该方法可以提供一个额外的参数 comparisonType,指定比较字符串时的方式。这个参数是一个枚举类型,包含如下几个取值:

  • CurrentCulture
  • CurrentCultureIgnoreCase
  • InvariantCulture
  • InvariantCultureIgnoreCase
  • Ordinal
  • OrdinalIgnoreCase

其中 CurrentCulture 表示使用当前线程使用的区域性进行字符串比较;InvariantCulture 则表示使用无区域性的排序规则进行字符串比较;而 Ordinal 比较字符串是基于字符串的基元(字符集)的数字值的比较。

下面是一个例子,我们使用 CurrentCultureIgnoreCase 参数进行比较:

string str = "hello world";
bool result = str.Contains("WORLD", StringComparison.CurrentCultureIgnoreCase);
Console.WriteLine(result); // 输出 true

在上面的代码中,我们将第二个参数设置为 StringComparison.CurrentCultureIgnoreCase,表示使用不区分大小写的区域性设置进行字符串比较。由于输入的字符串是大写的 WORLD,而原始字符串是小写的 world,因此结果为 true

总结

String.Contains() 方法在 C# 中常用于字符串的模糊匹配操作。通过指定参数 comparisonType,我们可以灵活地选择不同的字符串比较方式来满足不同的需求。以上就是 String.Contains() 方法的详细讲解及使用实例。