在C#中,可以使用string.Contains()方法来检查字符串是否包含特定的子串。string.Contains()方法接受一个参数,该参数是要搜索的子串,如果要搜索的子串存在于字符串中,则该方法将返回true,否则将返回false。
// 例如: string str1 = "This is a sample string"; bool result = str1.Contains("sample"); // result 为 true
string.Contains()方法也可以接受另一个可选参数,该参数指示是否使用不区分大小写的搜索。如果将该参数设置为true,则该方法将返回true,即使字符串中的字母的大小写不同也是如此。
// 例如: string str1 = "This is a sample string"; bool result = str1.Contains("Sample", true); // result 为 true
string.Contains()方法的另一个重要用途是检查字符串是否以特定的字符开头或结尾。例如,可以使用该方法检查字符串是否以“http”开头,或者检查字符串是否以“.com”结尾。
// 例如: string str1 = "http://www.example.com"; bool result1 = str1.StartsWith("http"); // result1 为 true bool result2 = str1.EndsWith(".com"); // result2 为 true
string.Contains()方法还可以用于检查字符串是否包含特定的字符,例如“@”或“#”等。
// 例如: string str1 = "This is a sample string"; bool result = str1.Contains("@"); // result 为 false
可以使用string.Contains()方法来检查字符串是否包含特定的子串,以及字符串是否以特定的字符开头或结尾,或者检查字符串是否包含特定的字符。