C# 字符串 - Contains() 方法
C# 字符串的 Contains() 方法用于根据特定的比较规则检查指定的子字符串是否存在于字符串中。如果存在,该方法将返回一个值,指示指定字符串在主字符串中的出现次数。
语法
以下是 C# 字符串的语法 Contains() 方法 -
public bool Contains (string value, StringComparison compareType);
参数
此方法接受以下参数 -
- value:要搜索的值。
- comparisonType:它是一个枚举值,用于指定比较中使用的规则。
返回值
如果字符串中存在 value 参数,则此方法返回 true
。如果值为空,则返回 空字符串
;否则,返回 false
。
示例 1:基本子字符串检查
以下是 Contains() 方法的基本示例,该方法用于检查字符串的子字符串 -
using System; class Program { static void Main() { string str = "Learning C# with tutorialspoint"; string substring = "C#"; bool result = str.Contains(substring); Console.WriteLine($"Does the string contain '{substring}'? {result}"); } }
输出
以下是输出 -
Does the string contain 'C#'? True
示例 2:区分大小写检查
让我们看一下 Contains() 方法的另一个示例。在这里,我们检查字符串是否区分大小写;如果不完全匹配,则返回 false -
using System; class Program { static void Main() { string str = "Hello, TutorialsPoint"; string substring = "hello"; bool result = str.Contains(substring); Console.WriteLine($"Case-sensitive check: {result}"); } }
输出
以下是输出 -
Case-sensitive check: False
示例 3:不区分大小写的检查
在此示例中,我们使用 Contains() 方法检查字符串是否不区分大小写;如果字符串匹配,则无论其大小写均返回 true −
using System; class Program { static void Main() { string str = "Hello, TutorialsPoint"; string substring = "hello"; bool result = str.Contains(substring, StringComparison.OrdinalIgnoreCase); Console.WriteLine($"Case-sensitive check: {result}"); } }
输出
以下是输出 -
Case-sensitive check: True
示例 4:使用特殊字符进行检查
我们还可以使用特殊字符作为子字符串,使用 Contains() 方法检查该子字符串是否存在于字符串中 -
using System; class Program { static void Main() { string str = "Hello C#"; string substring = "#"; bool result = str.Contains(substring); Console.WriteLine($"Does the string contain '{substring}'? {result}"); } }
输出
以下是输出 -
Does the string contain '#'? True