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.
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短