在C#中,String.Contains()是字串方法。此方法用於檢查子字串是否出現在給定的字串內。
語法:
public bool Contains(string str)
參數:
- str:這是要檢查的字串。參數的型別是System.String。
傳回值:它傳回布林值。如果子字串存在於字串中,或者value是空字串(“”),則傳回True,否則傳回False。
異常:如果str為null,則此方法可以會有ArgumentNullException異常。
注意:此方法執行區分大小寫的檢查。搜尋是從字串的第一個字元位置開始,一直持續到最後一個字元位置。
以下範例程式旨在說明Contains()方法。
程式1:
// C# program to demonstrate the // String.Contains() Method using System; class Geeks { // Main Method public static void Main() { // string type String str = "GeeksforGeeks"; String substr1 = "for"; String substr2 = "For"; // using String.Contains() Method Console.WriteLine(str.Contains(substr1)); // Here case-sensitive comparison // And substr2 value is 'For' // So its return false Console.WriteLine(str.Contains(substr2)); } }
輸出:
True False
程式2:使用順序比較和不區分大小寫的順序比較來確定字串中是否存在子字串。
// C# program to illustrate the // String.Contains() Method using // ordinal comparison and case- // insensitive ordinal comparison using System; public static class StringExtensions { // defines a String extension method // which includes a StringComparison parameter public static bool Contains(this String str, String substr, StringComparison cmp) { if (substr == null) throw new ArgumentNullException("substring substring", " cannot be null."); else if (!Enum.IsDefined(typeof(StringComparison), cmp)) throw new ArgumentException("comp is not a member of", "StringComparison, comp"); return str.IndexOf(substr, cmp) >= 0; } } // Driver Class class Geeks { // Main Method public static void Main() { String str = "GeeksforGeeks"; String substr = "FOR"; // For Ordinal StringComparison comp = StringComparison.Ordinal; Console.WriteLine("For {0:G}: {1}", comp, str.Contains(substr, comp)); // for OrdinalIgnoreCase comp = StringComparison.OrdinalIgnoreCase; Console.WriteLine("For {0:G}: {1}", comp, str.Contains(substr, comp)); } }
輸出:
For Ordinal: False For OrdinalIgnoreCase: True
程式3:下面的範例確定字串”Computer”是否為給定字串的子字串。如果在字串中找到它,它還會顯示其起始位置。這裡有動用到另一個IndexOf方法的使用,可以參考C# Substring 定義及七種用法
// C# program to demonstrate the // String.Contains() Method // along with the starting position using System; class Example { public static void Main() { string sub1 = "GeeksforGeeks is a Computer Science Portal"; string sub2 = "Computer"; // Check if the substring is // present in the main string bool b = sub1.Contains(sub2); Console.WriteLine("'{0}' is in the string '{1}': {2}", sub2, sub1, b); if (b) { int index = sub1.IndexOf(sub2); if (index >= 0) Console.WriteLine("{0} begins at character position {1}", sub2, index + 1); } } }
輸出:
'Computer' is in the string 'GeeksforGeeks is a Computer Science Portal': True Computer begins at character position 20
參考:https://docs.microsoft.com/zh-tw/dotnet/api/system.string.contains
註:本文由琪哥篩選整理自Mithun Kumar大神的英文原創作品 C# | String.Contains() Method。非經特殊聲明,原始碼版權歸原作者所有,本譯文的傳播和使用請遵循“姓名標示-相同方式分享 4.0 國際 (CC BY-SA 4.0)”協議。