檢查子串是否出現在給定字串中的 C# 程式
使用 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP