String.StartsWith 方法

定義

多載

StartsWith(String, Boolean, CultureInfo)

判斷當使用指定之文化特性進行比較時,這個字串執行個體的開頭是否符合指定的字串。

StartsWith(String, StringComparison)

判斷當使用指定之比較選項進行比較時,這個字串執行個體的開頭是否符合指定的字串。

StartsWith(Char)

判斷此字串執行個體是否以指定的字元開頭。

StartsWith(String)

判斷這個字串執行個體的開頭是否符合指定的字串。

StartsWith(String, Boolean, CultureInfo)

來源:
String.Comparison.cs
來源:
String.Comparison.cs
來源:
String.Comparison.cs

判斷當使用指定之文化特性進行比較時,這個字串執行個體的開頭是否符合指定的字串。

C#
public bool StartsWith (string value, bool ignoreCase, System.Globalization.CultureInfo? culture);
C#
public bool StartsWith (string value, bool ignoreCase, System.Globalization.CultureInfo culture);

參數

value
String

要比較的字串。

ignoreCase
Boolean

true 表示在比較時忽略大小寫,否則為 false

culture
CultureInfo

判斷如何比較此字串和 value 的文化特性資訊。 如果 culturenull,則會使用目前的文化特性。

傳回

如果 true 參數符合這個字串的開頭,則為 value,否則為 false

例外狀況

valuenull

範例

下列範例會判斷字串是否發生在另一個字串的開頭。 方法 StartsWith 會使用區分大小寫、不區分大小寫,以及影響搜尋結果的不同文化特性來呼叫數次。

C#
// This code example demonstrates the 
// System.String.StartsWith(String, ..., CultureInfo) method.

using System;
using System.Threading;
using System.Globalization;

class Sample 
{
    public static void Main() 
    {
    string msg1 = "Search for the target string \"{0}\" in the string \"{1}\".\n";
    string msg2 = "Using the {0} - \"{1}\" culture:";
    string msg3 = "  The string to search ends with the target string: {0}";
    bool result = false;
    CultureInfo ci;

// Define a target string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
    string capitalARing = "\u00c5";

// Define a string to search. 
// The result of combining the characters LATIN SMALL LETTER A and COMBINING 
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character 
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
    string aRingXYZ = "\u0061\u030a" + "xyz";

// Clear the screen and display an introduction.
    Console.Clear();

// Display the string to search for and the string to search.
    Console.WriteLine(msg1, capitalARing, aRingXYZ);

// Search using English-United States culture.
    ci = new CultureInfo("en-US");
    Console.WriteLine(msg2, ci.DisplayName, ci.Name);

    Console.WriteLine("Case sensitive:");
    result = aRingXYZ.StartsWith(capitalARing, false, ci);
    Console.WriteLine(msg3, result);

    Console.WriteLine("Case insensitive:");
    result = aRingXYZ.StartsWith(capitalARing, true, ci);
    Console.WriteLine(msg3, result);
    Console.WriteLine();

// Search using Swedish-Sweden culture.
    ci = new CultureInfo("sv-SE");
    Console.WriteLine(msg2, ci.DisplayName, ci.Name);

    Console.WriteLine("Case sensitive:");
    result = aRingXYZ.StartsWith(capitalARing, false, ci);
    Console.WriteLine(msg3, result);

    Console.WriteLine("Case insensitive:");
    result = aRingXYZ.StartsWith(capitalARing, true, ci);
    Console.WriteLine(msg3, result);
    }
}

/*
Note: This code example was executed on a console whose user interface 
culture is "en-US" (English-United States).

Search for the target string "Å" in the string "a°xyz".

Using the English (United States) - "en-US" culture:
Case sensitive:
  The string to search ends with the target string: False
Case insensitive:
  The string to search ends with the target string: True

Using the Swedish (Sweden) - "sv-SE" culture:
Case sensitive:
  The string to search ends with the target string: False
Case insensitive:
  The string to search ends with the target string: False

*/

備註

這個方法會將 value 參數與這個字串開頭的子字串進行比較,且長度與 value 相同,並傳回值,指出它們是否相等。 若要相等, value 必須是空字串 (String.Empty) 、必須是這個相同實例的參考,或必須符合這個實例的開頭。

此方法會使用指定的大小寫和文化特性來執行比較。

適用於

.NET 9 和其他版本
產品 版本
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

StartsWith(String, StringComparison)

來源:
String.Comparison.cs
來源:
String.Comparison.cs
來源:
String.Comparison.cs

判斷當使用指定之比較選項進行比較時,這個字串執行個體的開頭是否符合指定的字串。

C#
public bool StartsWith (string value, StringComparison comparisonType);
C#
[System.Runtime.InteropServices.ComVisible(false)]
public bool StartsWith (string value, StringComparison comparisonType);

參數

value
String

要比較的字串。

comparisonType
StringComparison

列舉值之一,指定這個字串和 value 的比較方式。

傳回

如果這個執行個體以 true 為開頭,則為 value,否則為 false

屬性

例外狀況

valuenull

comparisonType 不是 StringComparison 值。

範例

下列範例會在開頭為 「The」 這個字的較長字串開頭搜尋字串 「the」。 如範例的輸出所示,執行不區分文化特性但區分大小寫比較的方法呼叫 StartsWith(String, StringComparison) 無法比對字串,而執行文化特性和不區分大小寫比較的呼叫會比對字串。

C#
using System;

public class Example
{
   public static void Main()
   {
      String title = "The House of the Seven Gables";
      String searchString = "the";
      StringComparison comparison = StringComparison.InvariantCulture;
      Console.WriteLine("'{0}':", title);
      Console.WriteLine("   Starts with '{0}' ({1:G} comparison): {2}",
                        searchString, comparison,
                        title.StartsWith(searchString, comparison));

      comparison = StringComparison.InvariantCultureIgnoreCase;
      Console.WriteLine("   Starts with '{0}' ({1:G} comparison): {2}",
                        searchString, comparison,
                        title.StartsWith(searchString, comparison));
   }
}
// The example displays the following output:
//       'The House of the Seven Gables':
//          Starts with 'the' (InvariantCulture comparison): False
//          Starts with 'the' (InvariantCultureIgnoreCase comparison): True

下列範例會判斷字串是否以特定子字串開頭。 它會初始化二維字串陣列。 第二個維度中的第一個專案包含字串,而第二個元素則包含要在第一個字串開頭搜尋的字串。 結果會受到文化特性選擇的影響、是否忽略大小寫,以及是否執行序數比較。 請注意,當字串實例包含 Ligature 時,與連續字元的區分文化特性比較會順利比對。

C#
using System;

public class Example
{
   public static void Main()
   {
      string[,] strings = { {"ABCdef", "abc" },                    
                            {"ABCdef", "abc" },  
                            {"œil","oe" },
                            { "læring}", "lae" } };
      for (int ctr1 = strings.GetLowerBound(0); ctr1 <= strings.GetUpperBound(0); ctr1++)
      {
            foreach (string cmpName in Enum.GetNames(typeof(StringComparison)))
            { 
               StringComparison strCmp = (StringComparison) Enum.Parse(typeof(StringComparison), 
                                                      cmpName);
               string instance = strings[ctr1, 0];
               string value = strings[ctr1, 1];
               Console.WriteLine("{0} starts with {1}: {2} ({3} comparison)", 
                                 instance, value, 
                                 instance.StartsWith(value, strCmp), 
                                 strCmp); 
            }
            Console.WriteLine();   
      }   
   }
}
// The example displays the following output:
//       ABCdef starts with abc: False (CurrentCulture comparison)
//       ABCdef starts with abc: True (CurrentCultureIgnoreCase comparison)
//       ABCdef starts with abc: False (InvariantCulture comparison)
//       ABCdef starts with abc: True (InvariantCultureIgnoreCase comparison)
//       ABCdef starts with abc: False (Ordinal comparison)
//       ABCdef starts with abc: True (OrdinalIgnoreCase comparison)
//       
//       ABCdef starts with abc: False (CurrentCulture comparison)
//       ABCdef starts with abc: True (CurrentCultureIgnoreCase comparison)
//       ABCdef starts with abc: False (InvariantCulture comparison)
//       ABCdef starts with abc: True (InvariantCultureIgnoreCase comparison)
//       ABCdef starts with abc: False (Ordinal comparison)
//       ABCdef starts with abc: True (OrdinalIgnoreCase comparison)
//       
//       œil starts with oe: True (CurrentCulture comparison)
//       œil starts with oe: True (CurrentCultureIgnoreCase comparison)
//       œil starts with oe: True (InvariantCulture comparison)
//       œil starts with oe: True (InvariantCultureIgnoreCase comparison)
//       œil starts with oe: False (Ordinal comparison)
//       œil starts with oe: False (OrdinalIgnoreCase comparison)
//       
//       læring} starts with lae: True (CurrentCulture comparison)
//       læring} starts with lae: True (CurrentCultureIgnoreCase comparison)
//       læring} starts with lae: True (InvariantCulture comparison)
//       læring} starts with lae: True (InvariantCultureIgnoreCase comparison)
//       læring} starts with lae: False (Ordinal comparison)
//       læring} starts with lae: False (OrdinalIgnoreCase comparison)

備註

方法會將 StartsWith 參數與這個字串開頭的子字串進行比較 value ,並傳回值,指出它們是否相等。 若要相等, value 必須是這個相同字串的參考,必須是空字串 (「」) ,或必須符合此字串的開頭。 方法所 StartsWith 執行的比較類型取決於 參數的值 comparisonType 。 此比較可以使用目前文化特性的慣例 (StringComparison.CurrentCultureStringComparison.CurrentCultureIgnoreCase) 或不變異文化特性 (StringComparison.InvariantCultureStringComparison.InvariantCultureIgnoreCase) ,也可以由 (或 StringComparison.OrdinalIgnoreCase) 的程式碼點 StringComparison.Ordinal 逐字元比較所組成。 比較也可以區分大小寫 (StringComparison.CurrentCultureStringComparison.InvariantCultureStringComparison.Ordinal) ,也可以忽略大小寫 (StringComparison.CurrentCultureIgnoreCaseStringComparison.InvariantCultureIgnoreCase) StringComparison.OrdinalIgnoreCase

另請參閱

適用於

.NET 9 和其他版本
產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

StartsWith(Char)

來源:
String.Comparison.cs
來源:
String.Comparison.cs
來源:
String.Comparison.cs

判斷此字串執行個體是否以指定的字元開頭。

C#
public bool StartsWith (char value);

參數

value
Char

要比較的字元。

傳回

如果 true 符合這個字串的開頭,則為 value,否則為 false

備註

這個方法會執行區分大小寫且不區分文化特性的序數 (比較) 。

適用於

.NET 9 和其他版本
產品 版本
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Standard 2.1

StartsWith(String)

來源:
String.Comparison.cs
來源:
String.Comparison.cs
來源:
String.Comparison.cs

判斷這個字串執行個體的開頭是否符合指定的字串。

C#
public bool StartsWith (string value);

參數

value
String

要比較的字串。

傳回

如果 true 符合這個字串的開頭,則為 value,否則為 false

例外狀況

valuenull

範例

下列範例會 StripStartTags 定義方法,該方法會使用 StartsWith(String) 方法從字串開頭移除 HTML 起始標記。 請注意,此方法 StripStartTags 會以遞迴方式呼叫,以確保移除行開頭的多個 HTML 開始標記。 此範例不會移除內嵌在字串中的 HTML 標籤。

C#
using System;

public class Example
{
   public static void Main() {
      string [] strSource = { "<b>This is bold text</b>", "<H1>This is large Text</H1>",
                "<b><i><font color=green>This has multiple tags</font></i></b>",
                "<b>This has <i>embedded</i> tags.</b>",
                "<This line simply begins with a lesser than symbol, it should not be modified" };

      // Display the initial string array.
      Console.WriteLine("The original strings:");
      Console.WriteLine("---------------------");
      foreach (var s in strSource)
         Console.WriteLine(s);
      Console.WriteLine();

      Console.WriteLine("Strings after starting tags have been stripped:");
      Console.WriteLine("-----------------------------------------------");

      // Display the strings with starting tags removed.
     foreach (var s in strSource)
        Console.WriteLine(StripStartTags(s));
   }

   private static string StripStartTags(string item)
   {
      // Determine whether a tag begins the string.
      if (item.Trim().StartsWith("<")) {
         // Find the closing tag.
         int lastLocation = item.IndexOf( ">" );
         // Remove the tag.
         if (lastLocation >= 0) {
            item =  item.Substring( lastLocation + 1 );

            // Remove any additional starting tags.
            item = StripStartTags(item);
         }
      }

      return item;
   }
}
// The example displays the following output:
//    The original strings:
//    ---------------------
//    <b>This is bold text</b>
//    <H1>This is large Text</H1>
//    <b><i><font color = green>This has multiple tags</font></i></b>
//    <b>This has <i>embedded</i> tags.</b>
//    <This line simply begins with a lesser than symbol, it should not be modified
//
//    Strings after starting tags have been stripped:
//    -----------------------------------------------
//    This is bold text</b>
//    This is large Text</H1>
//    This has multiple tags</font></i></b>
//    This has <i>embedded</i> tags.</b>
//    <This line simply begins with a lesser than symbol, it should not be modified

備註

這個方法會 value 比較這個實例開頭的子字串,其長度與 value 相同,並傳回是否相等的指示。 若要相等, value 必須是空字串 (String.Empty) 、必須是這個相同實例的參考,或必須符合這個實例的開頭。

這個方法會使用目前文化特性來執行單字 (區分大小寫和區分文化特性) 比較。

給呼叫者的注意事項

使用字串的最佳做法中所述,建議您避免呼叫取代預設值的字串比較方法,而是呼叫需要明確指定參數的方法。 若要使用目前文化特性的字串比較規則,判斷字串是否以特定子字串開頭,請藉由呼叫 StartsWith(String, StringComparison) 方法多載,並為其 comparisonType 參數的值 CurrentCulture 明確發出訊號。 如果您不需要語言感知比較,請考慮使用 Ordinal

另請參閱

適用於

.NET 9 和其他版本
產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0