檢查子串是否出現在給定字串中的 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 次瀏覽

開啟你的 職業生涯

完成課程即獲得認證

開始
廣告
© . All rights reserved.