Läs på engelska Redigera

Dela via


String.StartsWith Method

Definition

Overloads

StartsWith(Char)

Determines whether this string instance starts with the specified character.

StartsWith(String)

Determines whether the beginning of this string instance matches the specified string.

StartsWith(String, StringComparison)

Determines whether the beginning of this string instance matches the specified string when compared using the specified comparison option.

StartsWith(String, Boolean, CultureInfo)

Determines whether the beginning of this string instance matches the specified string when compared using the specified culture.

StartsWith(Char)

Source:
String.Comparison.cs
Source:
String.Comparison.cs
Source:
String.Comparison.cs

Determines whether this string instance starts with the specified character.

public bool StartsWith (char value);

Parameters

value
Char

The character to compare.

Returns

true if value matches the beginning of this string; otherwise, false.

Remarks

This method performs an ordinal (case-sensitive and culture-insensitive) comparison.

Applies to

.NET 9 och andra versioner
Produkt Versioner
.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)

Source:
String.Comparison.cs
Source:
String.Comparison.cs
Source:
String.Comparison.cs

Determines whether the beginning of this string instance matches the specified string.

public bool StartsWith (string value);

Parameters

value
String

The string to compare.

Returns

true if value matches the beginning of this string; otherwise, false.

Exceptions

value is null.

Examples

The following example defines a StripStartTags method that uses the StartsWith(String) method to remove HTML start tags from the beginning of a string. Note that the StripStartTags method is called recursively to ensure that multiple HTML start tags at the beginning of the line are removed. The example does not remove HTML tags embedded in a string.

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

Remarks

This method compares value to the substring at the beginning of this instance that is the same length as value, and returns an indication whether they are equal. To be equal, value must be an empty string (String.Empty), must be a reference to this same instance, or must match the beginning of this instance.

This method performs a word (case-sensitive and culture-sensitive) comparison using the current culture.

Notes to Callers

As explained in Best Practices for Using Strings, we recommend that you avoid calling string comparison methods that substitute default values and instead call methods that require parameters to be explicitly specified. To determine whether a string begins with a particular substring by using the string comparison rules of the current culture, signal your intention explicitly by calling the StartsWith(String, StringComparison) method overload with a value of CurrentCulture for its comparisonType parameter. If you don't need linguistic-aware comparison, consider using Ordinal.

See also

Applies to

.NET 9 och andra versioner
Produkt Versioner
.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

StartsWith(String, StringComparison)

Source:
String.Comparison.cs
Source:
String.Comparison.cs
Source:
String.Comparison.cs

Determines whether the beginning of this string instance matches the specified string when compared using the specified comparison option.

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

Parameters

value
String

The string to compare.

comparisonType
StringComparison

One of the enumeration values that determines how this string and value are compared.

Returns

true if this instance begins with value; otherwise, false.

Attributes

Exceptions

value is null.

comparisonType is not a StringComparison value.

Examples

The following example searches for the string "the" at the beginning of a longer string that begins with the word "The". As the output from the example shows, a call to the StartsWith(String, StringComparison) method that performs a culture-insensitive but case-sensitive comparison fails to match the string, while a call that performs a culture- and case-insensitive comparison matches the string.

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

The following example determines whether a string starts with a particular substring. It initializes a two-dimensional string array. The first element in the second dimension contains a string, and the second element contains the string to search for at the start of the first string. The results are affected by the choice of culture, whether case is ignored, and whether an ordinal comparison is performed. Note that when the string instance contains a ligature, culture-sensitive comparisons with its consecutive characters successfully match.

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)

Remarks

The StartsWith method compares the value parameter to the substring at the beginning of this string and returns a value that indicates whether they are equal. To be equal, value must be a reference to this same string, must be the empty string (""), or must match the beginning of this string. The type of comparison performed by the StartsWith method depends on the value of the comparisonType parameter. The comparison can use the conventions of the current culture (StringComparison.CurrentCulture and StringComparison.CurrentCultureIgnoreCase) or the invariant culture (StringComparison.InvariantCulture and StringComparison.InvariantCultureIgnoreCase), or it can consist of a character-by-character comparison of code points (StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase). The comparison can also be case-sensitive (StringComparison.CurrentCulture, StringComparison.InvariantCulture, or StringComparison.Ordinal), or it can ignore case (StringComparison.CurrentCultureIgnoreCase, StringComparison.InvariantCultureIgnoreCase, StringComparison.OrdinalIgnoreCase).

See also

Applies to

.NET 9 och andra versioner
Produkt Versioner
.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(String, Boolean, CultureInfo)

Source:
String.Comparison.cs
Source:
String.Comparison.cs
Source:
String.Comparison.cs

Determines whether the beginning of this string instance matches the specified string when compared using the specified culture.

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

Parameters

value
String

The string to compare.

ignoreCase
Boolean

true to ignore case during the comparison; otherwise, false.

culture
CultureInfo

Cultural information that determines how this string and value are compared. If culture is null, the current culture is used.

Returns

true if the value parameter matches the beginning of this string; otherwise, false.

Exceptions

value is null.

Examples

The following example determines whether a string occurs at the beginning of another string. The StartsWith method is called several times using case sensitivity, case insensitivity, and different cultures that influence the results of the search.

// 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

*/

Remarks

This method compares the value parameter to the substring at the beginning of this string that is the same length as value, and returns a value that indicates whether they are equal. To be equal, value must be an empty string (String.Empty), must be a reference to this same instance, or must match the beginning of this instance.

This method performs a comparison using the specified casing and culture.

Applies to

.NET 9 och andra versioner
Produkt Versioner
.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