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

更新於:19-Jun-2020

497 次瀏覽

開啟你的 職業生涯

完成課程,獲取認證

開始
Advertisement
© . All rights reserved.