Compartir vía


String.EndsWith Método

Definición

Determina si el final de esta instancia de cadena coincide con una cadena especificada.

Sobrecargas

EndsWith(String, Boolean, CultureInfo)

Determina si el final de esta instancia de cadena coincide con la cadena especificada cuando se comparan usando la referencia cultural especificada.

EndsWith(String, StringComparison)

Determina si el final de esta instancia de cadena coincide con la cadena especificada cuando se comparan usando la opción de comparación especificada.

EndsWith(Char)

Determina si el final de esta instancia de cadena coincide con el carácter especificado.

EndsWith(String)

Determina si el final de esta instancia de cadena coincide con la cadena especificada.

EndsWith(String, Boolean, CultureInfo)

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

Determina si el final de esta instancia de cadena coincide con la cadena especificada cuando se comparan usando la referencia cultural especificada.

public:
 bool EndsWith(System::String ^ value, bool ignoreCase, System::Globalization::CultureInfo ^ culture);
public bool EndsWith (string value, bool ignoreCase, System.Globalization.CultureInfo? culture);
public bool EndsWith (string value, bool ignoreCase, System.Globalization.CultureInfo culture);
member this.EndsWith : string * bool * System.Globalization.CultureInfo -> bool
Public Function EndsWith (value As String, ignoreCase As Boolean, culture As CultureInfo) As Boolean

Parámetros

value
String

Cadena que se va a comparar con la subcadena situada al final de esta instancia.

ignoreCase
Boolean

true para no distinguir entre mayúsculas y minúsculas durante la comparación; de lo contrario, false.

culture
CultureInfo

Información de referencia cultural que determina cómo se comparan esta instancia y value. Si culture es null, se usa la referencia cultural actual.

Devoluciones

Es true si el parámetro value coincide con el final de esta cadena; en caso contrario, es false.

Excepciones

value es null.

Ejemplos

En el ejemplo siguiente se determina si una cadena se produce al final de otra cadena. El EndsWith método se llama varias veces mediante distinción entre mayúsculas y minúsculas, distinción entre mayúsculas y minúsculas y referencias culturales diferentes que influyen en los resultados de la búsqueda.

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

*/
// This code example demonstrates the 
// System.String.EndsWith(String, ..., CultureInfo) method.
open System.Globalization

[<EntryPoint>]
let main _ =
    // Define a target string to search for.
    // U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
    let 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).
    let xyzARing = "xyz" + "\u0061\u030a"

    // Display the string to search for and the string to search.
    printfn $"Search for the target string \"{capitalARing}\" in the string \"{xyzARing}\".\n"

    // Search using English-United States culture.
    let ci = CultureInfo "en-US"
    printfn $"Using the {ci.DisplayName} - \"{ci.Name}\" culture:"

    printfn "Case sensitive:"
    let result = xyzARing.EndsWith(capitalARing, false, ci)
    printfn $"  The string to search ends with the target string: {result}"

    printfn "Case insensitive:"
    let result = xyzARing.EndsWith(capitalARing, true, ci)
    printfn $"  The string to search ends with the target string: {result}\n"

    // Search using Swedish-Sweden culture.
    let ci = CultureInfo "sv-SE"
    printfn $"Using the {ci.DisplayName} - \"{ci.Name}\" culture:"

    printfn "Case sensitive:"
    let result = xyzARing.EndsWith(capitalARing, false, ci)
    printfn $"  The string to search ends with the target string: {result}"

    printfn "Case insensitive:"
    let result = xyzARing.EndsWith(capitalARing, true, ci)
    printfn $"  The string to search ends with the target string: {result}"
    0
(*
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
*)
' This code example demonstrates the 
' System.String.EndsWith(String, ..., CultureInfo) method.

Imports System.Threading
Imports System.Globalization

Class Sample
    Public Shared Sub Main() 
        Dim msg1 As String = "Search for the target string ""{0}"" in the string ""{1}""." & vbCrLf
        Dim msg2 As String = "Using the {0} - ""{1}"" culture:"
        Dim msg3 As String = "  The string to search ends with the target string: {0}"
        Dim result As Boolean = False
        Dim ci As CultureInfo
        
        ' Define a target string to search for.
        ' U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
        Dim capitalARing As String = "Å"
        
        ' 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).
        Dim xyzARing As String = "xyz" & "å"
               
        ' 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)
    
    End Sub
End Class

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

Comentarios

Este método compara el value parámetro con la subcadena al final de esta cadena que es la misma longitud valueque y devuelve un valor que indica si son iguales. Para ser igual, value debe ser una referencia a esta misma instancia o coincidir con el final de esta cadena.

Este método realiza una comparación de palabras (que distingue la referencia cultural) mediante el uso de mayúsculas y minúsculas y referencias culturales especificados.

Consulte también

Se aplica a

EndsWith(String, StringComparison)

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

Determina si el final de esta instancia de cadena coincide con la cadena especificada cuando se comparan usando la opción de comparación especificada.

public:
 bool EndsWith(System::String ^ value, StringComparison comparisonType);
public bool EndsWith (string value, StringComparison comparisonType);
[System.Runtime.InteropServices.ComVisible(false)]
public bool EndsWith (string value, StringComparison comparisonType);
member this.EndsWith : string * StringComparison -> bool
[<System.Runtime.InteropServices.ComVisible(false)>]
member this.EndsWith : string * StringComparison -> bool
Public Function EndsWith (value As String, comparisonType As StringComparison) As Boolean

Parámetros

value
String

Cadena que se va a comparar con la subcadena situada al final de esta instancia.

comparisonType
StringComparison

Uno de los valores de enumeración que determina cómo se comparan esta cadena y value.

Devoluciones

Es true si el parámetro value coincide con el final de esta cadena; en caso contrario, es false.

Atributos

Excepciones

value es null.

comparisonType no es un valor StringComparison.

Ejemplos

En el ejemplo siguiente se determina si una cadena termina con una subcadena determinada. Los resultados se ven afectados por la elección de la referencia cultural, si se omiten mayúsculas y minúsculas y si se realiza una comparación ordinal.

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

using namespace System;
using namespace System::Threading;

void Test(String^ testString, String^ searchString, 
     StringComparison comparison)
{
    String^ resultFormat = "\"{0}\" {1} with \"{2}\".";
    String^ resultString = "does not end";

    if (testString->EndsWith(searchString, comparison))
    {
        resultString = "ends";
    }
    Console::WriteLine(resultFormat, testString, resultString, searchString);
}

int main()
{
    String^ introMessage =
        "Determine whether a string ends with another string, " +
        "using\ndifferent values of StringComparison.";

    array<StringComparison>^ comparisonValues = {
        StringComparison::CurrentCulture,
        StringComparison::CurrentCultureIgnoreCase,
        StringComparison::InvariantCulture,
        StringComparison::InvariantCultureIgnoreCase,
        StringComparison::Ordinal,
        StringComparison::OrdinalIgnoreCase};

    Console::WriteLine(introMessage);

    // 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);
    // Perform two tests for each StringComparison
    for each (StringComparison stringCmp in comparisonValues)
    {
        Console::WriteLine("StringComparison.{0}:", stringCmp);
        Test("abcXYZ", "XYZ", stringCmp);
        Test("abcXYZ", "xyz", stringCmp);
        Console::WriteLine();
    }
}

/*
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".

*/
// 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".

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

open System
open System.Threading

let test (x: string) y (comparison: StringComparison) =
    let result = 
        if x.EndsWith(y, comparison) then
            "ends"
        else 
            "does not end"
    printfn $"\"{x}\" {result} with \"{y}\"."

let scValues = 
  [|
    StringComparison.CurrentCulture
    StringComparison.CurrentCultureIgnoreCase
    StringComparison.InvariantCulture
    StringComparison.InvariantCultureIgnoreCase
    StringComparison.Ordinal
    StringComparison.OrdinalIgnoreCase
  |]

printfn "Determine whether a string ends with another string, using\n  different values of StringComparison."

// Display the current culture because the culture-specific comparisons
// can produce different results with different cultures.
printfn $"The current culture is {Thread.CurrentThread.CurrentCulture.Name}.\n"

// Determine whether three versions of the letter I are equal to each other. 
for sc in scValues do
    printfn $"StringComparison.{sc}:"
    test "abcXYZ" "XYZ" sc
    test "abcXYZ" "xyz" sc
    printfn ""

(*
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".

*)
' This example demonstrates the 
' System.String.EndsWith(String, StringComparison) method.

Imports System.Threading

Class Sample
    Public Shared Sub Main() 
        Dim intro As String = "Determine whether a string ends with another string, " & _
                              "using" & vbCrLf & "  different values of StringComparison."
        
        Dim scValues As StringComparison() =  { _
                        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}." & vbCrLf, _
                           Thread.CurrentThread.CurrentCulture.Name)

        ' Determine whether three versions of the letter I are equal to each other. 
        Dim sc As StringComparison
        For Each sc In  scValues
            Console.WriteLine("StringComparison.{0}:", sc)
            Test("abcXYZ", "XYZ", sc)
            Test("abcXYZ", "xyz", sc)
            Console.WriteLine()
        Next sc
    
    End Sub
    
    
    Protected Shared Sub Test(ByVal x As String, ByVal y As String, _
                              ByVal comparison As StringComparison) 
        Dim resultFmt As String = """{0}"" {1} with ""{2}""."
        Dim result As String = "does not end"
        '
        If x.EndsWith(y, comparison) Then
            result = "ends"
        End If
        Console.WriteLine(resultFmt, x, result, y)
    
    End Sub
End Class

'
'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".
'

Comentarios

El EndsWith método compara el value parámetro con la subcadena al final de esta cadena y devuelve un valor que indica si son iguales. Para ser igual, value debe ser una referencia a esta misma cadena, debe ser la cadena vacía ("") o debe coincidir con el final de esta cadena. El tipo de comparación realizado por el EndsWith método depende del valor del comparisonType parámetro .

Consulte también

Se aplica a

EndsWith(Char)

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

Determina si el final de esta instancia de cadena coincide con el carácter especificado.

public:
 bool EndsWith(char value);
public bool EndsWith (char value);
member this.EndsWith : char -> bool
Public Function EndsWith (value As Char) As Boolean

Parámetros

value
Char

El carácter que se va a comparar con el carácter situado al final de esta instancia.

Devoluciones

Es true si value coincide con el final de esta instancia; en caso contrario, es false.

Comentarios

Este método realiza una comparación ordinal (sin distinción entre mayúsculas y minúsculas y sin distinción entre referencias culturales).

Se aplica a

EndsWith(String)

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

Determina si el final de esta instancia de cadena coincide con la cadena especificada.

public:
 bool EndsWith(System::String ^ value);
public bool EndsWith (string value);
member this.EndsWith : string -> bool
Public Function EndsWith (value As String) As Boolean

Parámetros

value
String

Cadena que se va a comparar con la subcadena situada al final de esta instancia.

Devoluciones

Es true si value coincide con el final de esta instancia; en caso contrario, es false.

Excepciones

value es null.

Ejemplos

En el ejemplo siguiente se indica si cada cadena de una matriz finaliza con un punto (".").

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
let strings = 
    [| "This is a string."; "Hello!"; "Nothing."
       "Yes."; "randomize" |]

for value in strings do
    let endsInPeriod = value.EndsWith "."
    printfn $"'{value}' ends in a period: {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
Module Example
   Public Sub Main()
      Dim strings() As String = { "This is a string.", "Hello!", 
                                  "Nothing.", "Yes.", "randomize" }
      For Each value In strings
         Dim endsInPeriod As Boolean = value.EndsWith(".")
         Console.WriteLine("'{0}' ends in a period: {1}", 
                           value, endsInPeriod)
      Next                            
   End Sub
End Module
' 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

En el ejemplo siguiente se define un StripEndTags método que usa el EndsWith(String) método para quitar etiquetas finales HTML del final de una línea. Tenga en cuenta que el StripEndTags método se llama de forma recursiva para asegurarse de que se quitan varias etiquetas de extremo HTML al final de la línea.

using namespace System;
using namespace System::Collections;

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 ) {
            item = item->Substring( 0, lastLocation );
            found = true;
      }
   }

   if (found) item = StripEndTags(item);
   
   return item;
}

int 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 (>).
   array<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
   IEnumerator^ myEnum1 = strSource->GetEnumerator();
   while ( myEnum1->MoveNext() )
   {
      String^ s = safe_cast<String^>(myEnum1->Current);
      Console::WriteLine( s );
   }

   Console::WriteLine();
   Console::WriteLine( "The following lists the items after the ends have been stripped:" );
   Console::WriteLine( "----------------------------------------------------------------" );
   
   // Display the array of strings.
   IEnumerator^ myEnum2 = strSource->GetEnumerator();
   while ( myEnum2->MoveNext() )
   {
      String^ s = safe_cast<String^>(myEnum2->Current);
      Console::WriteLine( StripEndTags( s ) );
   }
}
// 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>
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>
let rec stripEndTags item =
    let mutable item: string = item
    let mutable found = false

    // try to find a tag at the end of the line using EndsWith
    if item.Trim().EndsWith ">" then
        // now search for the opening tag...
        let lastLocation = item.LastIndexOf "</"

        // remove the identified section, if it is a valid region
        if lastLocation >= 0 then
            found <- true
            item <- item.Substring(0, lastLocation)

    if found then
        stripEndTags item
    else 
        item

// 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 (>).

let 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>" |]

printfn "The following lists the items before the ends have been stripped:"
printfn "-----------------------------------------------------------------"

// print out the initial array of strings
for s in strSource do
    printfn $"{s}"

printfn "\nThe following lists the items after the ends have been stripped:"
printfn "----------------------------------------------------------------"

// print out the array of strings
for s in strSource do
    printfn $"{stripEndTags s}"

// 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>
Public Module Example
    Public Sub Main()
        Dim strSource() As String = { "<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("-----------------------------------------------------------------")

        ' Display the initial array of strings.
        For Each s As String In  strSource
            Console.WriteLine(s)
        Next
        Console.WriteLine()

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

        ' Display the array of strings.
        For Each s As String In strSource
            Console.WriteLine(StripEndTags(s))
        Next 
    End Sub 

    Private Function StripEndTags(item As String) As String
        Dim found As Boolean = False
        
        ' Try to find a tag at the end of the line using EndsWith.
        If item.Trim().EndsWith(">") Then
            ' now search for the opening tag...
            Dim lastLocation As Integer = item.LastIndexOf("</")
            If lastLocation >= 0 Then
                found = True
                
                ' Remove the identified section, if it is a valid region.
                item = item.Substring(0, lastLocation)
            End If
        End If
        
        If found Then item = StripEndTags(item)
        Return item
    End Function 
End Module
' 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>

Comentarios

Este método se compara con value la subcadena al final de esta instancia que tiene la misma longitud valueque y devuelve una indicación de si son iguales. Para ser igual, value debe ser una referencia a esta misma instancia o coincidir con el final de esta instancia.

Este método realiza una comparación de palabras (distingue mayúsculas de minúsculas y distingue referencias culturales) mediante la referencia cultural actual.

Notas a los autores de las llamadas

Como se explica en Procedimientos recomendados para usar cadenas, se recomienda evitar llamar a métodos de comparación de cadenas que sustituya los valores predeterminados y, en su lugar, llame a métodos que requieren que se especifiquen explícitamente parámetros. Para determinar si una cadena termina con una subcadena determinada mediante las reglas de comparación de cadenas de la referencia cultural actual, indique su intención explícitamente llamando a la sobrecarga del EndsWith(String, StringComparison) método con un valor de CurrentCulture para su comparisonType parámetro. Si no necesita una comparación con reconocimiento lingüístico, considere la posibilidad de usar Ordinal.

Consulte también

Se aplica a