如何在 C# 中從字串中查詢子字串?


設定字串

string s = "Tom Cruise";

現在,假設你需要查詢子字串“Tom”,那麼請使用 Contains() 方法。

if (s.Contains("Tom") == true) {
   Console.WriteLine("Substring found!");
}

以下是如何查詢字串中子字串的程式碼 -

示例

 即時演示

using System;

public class Demo {
   public static void Main() {
      string s = "Tom Cruise";

      if (s.Contains("Tom") == true) {
         Console.WriteLine("Substring found!");
      } else {
         Console.WriteLine("Substring not found!");
      }
   }
}

輸出

Substring found!

更新於:22-Jun-2020

230 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.