如何在 C# 中从字符串中查找子字符串?

csharpprogrammingserver side programming更新于 2025/5/27 1:37:17

设置字符串

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!

相关文章