String.Contains()方法以及C#中的示例
C#方法String.Contains()
String.Contains()方法用于检查给定的字符串是否包含子字符串,当需要检查字符串的一部分(子字符串)是否存在时,可以使用此方法。
语法:
bool String.Contains(String substring);
用“this”字符串调用该方法,即我们必须在其中检查子字符串的字符串。
参数:
substring–是要检查的字符串的一部分。
返回值:
bool-如果字符串中不存在子字符串,则返回“True”;如果字符串中不存在子字符串,则返回“False”。
注意:此方法区分大小写。
示例
Input:
string str = "Hello world!";
string str1 = "world";
string str2 = "Hi";
Function call:
str.Contains(str1);
str.Contains(str2);
Output:
True
FalseC#使用方法将字符串转换为字符数组的示例String.Contains()
范例1:
using System;
class nhooo
{
static void Main()
{
//声明字符串变量
string str = "Hello world!";
string str1 = "world";
string str2 = "Hi";
//检查子串
Console.WriteLine("str.Contains(str1): " + str.Contains(str1));
Console.WriteLine("str.Contains(str2): " + str.Contains(str2));
}
}输出结果
str.Contains(str1): True str.Contains(str2): False
范例2:
using System;
class nhooo
{
static void Main()
{
//声明字符串变量
string address = "102, Nehru Place, New Delhi, India.";
string area1 = "Nehru Place";
string area2 = "Sant Nagar";
//检查并打印结果
if (address.Contains(area1))
{
Console.WriteLine(area1 + " exists in the address " + address);
}
else
{
Console.WriteLine(area1 + " does not exist in the address " + address);
}
if (address.Contains(area2))
{
Console.WriteLine(area2 + " exists in the address " + address);
}
else
{
Console.WriteLine(area2 + " does not exist in the address " + address);
}
}
}输出结果
Nehru Place exists in the address 102, Nehru Place, New Delhi, India. Sant Nagar does not exist in the address 102, Nehru Place, New Delhi, India.