C# 程序检查给定字符串中是否存在子字符串
csharpserver side programmingprogramming更新于 2025/9/24 20:24:00
使用 C# 中的 contains() 方法检查给定字符串中是否存在子字符串。
假设字符串为 −
United
在字符串中,您需要找到子字符串"Uni"。为此,使用 contains 方法并像以下代码片段 −
res = str1.Contains(str2);
示例
您可以尝试运行以下代码来查找字符串中的子字符串。
using System;
public class Demo {
public static void Main() {
string str1 = "United", str2 = "Uni";
bool res;
res = str1.Contains(str2);
if (res)
Console.Write("The substring " + str2 + " is in the string " + str1);
else
Console.Write("The substring " + str2 + " is not in the string " + str1);
}
}
输出
The substring Uni is in the string United

