String.EndsWith Метод

Определение

Определяет, совпадает ли конец данного экземпляра строки с указанной строкой.

Перегрузки

EndsWith(String, Boolean, CultureInfo)

Определяет, совпадает ли конец данного экземпляра строки с заданной строкой при сравнении с учетом заданного языка и региональных параметров.

EndsWith(String, StringComparison)

Определяет, совпадает ли конец экземпляра строки с заданной строкой при сравнении с учетом заданного параметра сравнения.

EndsWith(Char)

Определяет, совпадает ли конец данного экземпляра строки с указанным символом.

EndsWith(String)

Определяет, совпадает ли конец данного экземпляра строки с указанной строкой.

EndsWith(String, Boolean, CultureInfo)

Исходный код:
String.Comparison.cs
Исходный код:
String.Comparison.cs
Исходный код:
String.Comparison.cs

Определяет, совпадает ли конец данного экземпляра строки с заданной строкой при сравнении с учетом заданного языка и региональных параметров.

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

Параметры

value
String

Строка, которую необходимо сравнить с подстрокой, расположенной в конце этого экземпляра.

ignoreCase
Boolean

Значение true, чтобы не учитывать регистр при сравнении; в противном случае — значение false.

culture
CultureInfo

Связанные с языком и региональными параметрами сведения, определяющие, как выполняется сравнение этого экземпляра и value. Если значением параметра culture является null, используется текущий язык и региональные параметры.

Возвращаемое значение

true, если параметр value соответствует концу данной строки; в противном случае — false.

Исключения

value имеет значение null.

Примеры

В следующем примере определяется, находится ли строка в конце другой строки. Метод EndsWith вызывается несколько раз с учетом регистра, учетом регистра и различными языками и региональными параметрами, которые влияют на результаты поиска.

C#
// This code example demonstrates the 
// System.String.EndsWith(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 xyzARing = "xyz" + "\u0061\u030a";

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

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

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

        Console.WriteLine("Case insensitive:");
        result = xyzARing.EndsWith(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 = xyzARing.EndsWith(capitalARing, false, ci);
        Console.WriteLine(msg3, result);

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

/*
This code example produces the following results (for en-us culture):

Search for the target string "Å" in the string "xyza°".

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 должен быть ссылкой на этот же экземпляр или соответствовать концу этой строки.

Этот метод выполняет сравнение слов (с учетом языка и региональных параметров), используя указанные регистр и язык и региональные параметры.

См. также раздел

Применяется к

.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

EndsWith(String, StringComparison)

Исходный код:
String.Comparison.cs
Исходный код:
String.Comparison.cs
Исходный код:
String.Comparison.cs

Определяет, совпадает ли конец экземпляра строки с заданной строкой при сравнении с учетом заданного параметра сравнения.

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

Параметры

value
String

Строка, которую необходимо сравнить с подстрокой, расположенной в конце этого экземпляра.

comparisonType
StringComparison

Одно из значений перечисления, определяющее способ сравнения данной строки со значением value.

Возвращаемое значение

true, если параметр value соответствует концу данной строки; в противном случае — false.

Атрибуты

Исключения

value имеет значение null.

comparisonType не является значением StringComparison.

Примеры

В следующем примере определяется, заканчивается ли строка определенной подстрокой. На результаты влияет выбор языка и региональных параметров, игнорируется ли регистр и выполняется порядковый номер сравнения.

C#
// This example demonstrates the 
// System.String.EndsWith(String, StringComparison) method.

using System;
using System.Threading;

class Sample 
{
    public static void Main() 
    {
        string intro = "Determine whether a string ends with another string, " +
                   "using\n  different values of StringComparison.";

        StringComparison[] scValues = {
            StringComparison.CurrentCulture,
            StringComparison.CurrentCultureIgnoreCase,
            StringComparison.InvariantCulture,
            StringComparison.InvariantCultureIgnoreCase,
            StringComparison.Ordinal,
            StringComparison.OrdinalIgnoreCase };

        Console.WriteLine(intro);

        // Display the current culture because the culture-specific comparisons
        // can produce different results with different cultures.
        Console.WriteLine("The current culture is {0}.\n", 
                       Thread.CurrentThread.CurrentCulture.Name);
        
        // Determine whether three versions of the letter I are equal to each other. 
        foreach (StringComparison sc in scValues)
        {
            Console.WriteLine("StringComparison.{0}:", sc);
            Test("abcXYZ", "XYZ", sc);
            Test("abcXYZ", "xyz", sc);
            Console.WriteLine();
        }
    }

    protected static void Test(string x, string y, StringComparison comparison)
    {
        string resultFmt = "\"{0}\" {1} with \"{2}\".";
        string result = "does not end";

        if (x.EndsWith(y, comparison))
            result = "ends";
        Console.WriteLine(resultFmt, x, result, y);
    }
}

/*
This code example produces the following results:

Determine whether a string ends with another string, using
  different values of StringComparison.
The current culture is en-US.

StringComparison.CurrentCulture:
"abcXYZ" ends with "XYZ".
"abcXYZ" does not end with "xyz".

StringComparison.CurrentCultureIgnoreCase:
"abcXYZ" ends with "XYZ".
"abcXYZ" ends with "xyz".

StringComparison.InvariantCulture:
"abcXYZ" ends with "XYZ".
"abcXYZ" does not end with "xyz".

StringComparison.InvariantCultureIgnoreCase:
"abcXYZ" ends with "XYZ".
"abcXYZ" ends with "xyz".

StringComparison.Ordinal:
"abcXYZ" ends with "XYZ".
"abcXYZ" does not end with "xyz".

StringComparison.OrdinalIgnoreCase:
"abcXYZ" ends with "XYZ".
"abcXYZ" ends with "xyz".

*/

Комментарии

Метод EndsWith сравнивает value параметр с подстрокой в конце этой строки и возвращает значение, указывающее, равны ли они. Чтобы быть равным, value должен быть ссылкой на эту же строку, должен быть пустой строкой (""), или должен соответствовать концу этой строки. Тип сравнения, выполняемого методом , EndsWith зависит от значения comparisonType параметра .

См. также раздел

Применяется к

.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

EndsWith(Char)

Исходный код:
String.Comparison.cs
Исходный код:
String.Comparison.cs
Исходный код:
String.Comparison.cs

Определяет, совпадает ли конец данного экземпляра строки с указанным символом.

C#
public bool EndsWith (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

EndsWith(String)

Исходный код:
String.Comparison.cs
Исходный код:
String.Comparison.cs
Исходный код:
String.Comparison.cs

Определяет, совпадает ли конец данного экземпляра строки с указанной строкой.

C#
public bool EndsWith (string value);

Параметры

value
String

Строка, которую необходимо сравнить с подстрокой, расположенной в конце этого экземпляра.

Возвращаемое значение

true, если конец этого экземпляра совпадает с value; в противном случае — false.

Исключения

value имеет значение null.

Примеры

В следующем примере показано, заканчивается ли каждая строка в массиве точкой (".").

C#
using System;

public class Example
{
   public static void Main()
   {
      String[] strings = { "This is a string.", "Hello!", "Nothing.", 
                           "Yes.", "randomize" };
      foreach (var value in strings) {
         bool endsInPeriod = value.EndsWith(".");
         Console.WriteLine("'{0}' ends in a period: {1}", 
                           value, endsInPeriod);
      }                            
   }
}
// The example displays the following output:
//       'This is a string.' ends in a period: True
//       'Hello!' ends in a period: False
//       'Nothing.' ends in a period: True
//       'Yes.' ends in a period: True
//       'randomize' ends in a period: False

В следующем примере определяется StripEndTags метод , который использует EndsWith(String) метод для удаления конечных тегов HTML из конца строки. Обратите внимание, что StripEndTags метод вызывается рекурсивно, чтобы гарантировать удаление нескольких конечных тегов HTML в конце строки.

C#
using System;

public class EndsWithTest {
    public static void Main() {

        // process an input file that contains html tags.
        // this sample checks for multiple tags at the end of the line, rather than simply
        // removing the last one.
        // note: HTML markup tags always end in a greater than symbol (>).

        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 ends with a greater than symbol, it should not be modified>" };

        Console.WriteLine("The following lists the items before the ends have been stripped:");
        Console.WriteLine("-----------------------------------------------------------------");

        // print out the initial array of strings
        foreach ( string s in strSource )
            Console.WriteLine( s );

        Console.WriteLine();

        Console.WriteLine("The following lists the items after the ends have been stripped:");
        Console.WriteLine("----------------------------------------------------------------");

        // print out the array of strings
        foreach (var s in strSource)
            Console.WriteLine(StripEndTags(s));
    }

    private static string StripEndTags( string item ) {

        bool found = false;

        // try to find a tag at the end of the line using EndsWith
        if (item.Trim().EndsWith(">")) {

            // now search for the opening tag...
            int lastLocation = item.LastIndexOf( "</" );

            // remove the identified section, if it is a valid region
            if ( lastLocation >= 0 ) {
                found = true;
                item =  item.Substring( 0, lastLocation );
            }
        }

        if (found)
           item = StripEndTags(item);

        return item;
    }
}
// The example displays the following output:
//    The following lists the items before the ends have been stripped:
//    -----------------------------------------------------------------
//    <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 ends with a greater than symbol, it should not be modified>
//
//    The following lists the items after the ends have been stripped:
//    ----------------------------------------------------------------
//    <b>This is bold text
//    <H1>This is large Text
//    <b><i><font color=green>This has multiple tags
//    <b>This has <i>embedded</i> tags.
//    This line simply ends with a greater than symbol, it should not be modified>

Комментарии

Этот метод сравнивает value подстроку в конце экземпляра, которая имеет ту же длину value, что и , и возвращает значение, указывающее, равны ли они. Чтобы быть равным, value должен быть ссылкой на этот же экземпляр или соответствовать концу этого экземпляра.

Этот метод выполняет сравнение слов (с учетом регистра и языка и региональных параметров) с использованием текущего языка и региональных параметров.

Примечания для тех, кто вызывает этот метод

Как описано в разделе Рекомендации по использованию строк, рекомендуется не вызывать методы сравнения строк, заменяющие значения по умолчанию, и вместо этого вызывать методы, требующие явного указания параметров. Чтобы определить, заканчивается ли строка определенной подстрокой с помощью правил сравнения строк текущего языка и региональных параметров, явно сообщите о своем намерении, вызвав перегрузку EndsWith(String, StringComparison) метода со значением CurrentCulture для параметра comparisonType . Если вам не требуется лингвистическое сравнение, рассмотрите возможность использования 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