Esta documentación está archivada y no tiene mantenimiento.

String.LastIndexOf (Método) (String)

Actualización: noviembre 2007

Devuelve la posición de índice de la última aparición de un objeto String especificado en la instancia.

Espacio de nombres:  System
Ensamblado:  mscorlib (en mscorlib.dll)

public int LastIndexOf(
	string value
)
public int LastIndexOf(
	String value
)
public function LastIndexOf(
	value : String
) : int

Parámetros

value
Tipo: System.String
String que se va a buscar.

Valor devuelto

Tipo: System.Int32
Posición de índice de value si se encuentra la cadena; en caso contrario, -1. Si value es Empty, el valor devuelto es la última posición de índice en esta instancia.

ExcepciónCondición
ArgumentNullException

El valor de value es null.

La numeración de los índices empieza por cero. Es decir, el primer carácter de la cadena está en el índice cero y el último está en Length - 1.

La búsqueda comienza en la última posición de carácter de esta instancia y va retrocediendo hacia el principio hasta que se encuentra value o se examina la primera posición de carácter.

Este método realiza una búsqueda de palabras (donde se distinguen mayúsculas de minúsculas y la referencia cultural) utilizando la referencia cultural actual.

En el siguiente ejemplo de código se muestra cómo se puede utilizar el método LastIndexOf para tomar decisiones mientras se analiza la entrada de cadenas.

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 ( string s in strSource )
            Console.WriteLine( StripEndTags( s ) );
    }

    private static string StripEndTags( string item ) {

            // 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 );
            }

    return item;
    }
}


import System.*;

public class EndsWithTest
{
    public static void main(String[] args)
    {
        // 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
        for (int iCtr = 0; iCtr < strSource.get_Length(); iCtr++) {
            String s = (String)strSource.get_Item(iCtr);
            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
        for (int iCtr = 0; iCtr < strSource.get_Length(); iCtr++) {
            String s = (String)strSource.get_Item(iCtr);
            Console.WriteLine(StripEndTags(s));
        }
    } //main

    private static String StripEndTags(String item)
    {
        // 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);
            }
        }
        return item;
    } //StripEndTags
} //EndsWithTest


import System;

public class EndsWithTest {
    public static function Main() : void {

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

        var strSource : 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("-----------------------------------------------------------------");

        // print out the initial array of strings
        for( var i : int in strSource )
            Console.WriteLine( strSource[i] );

        Console.WriteLine();
        Console.WriteLine("The following lists the items after the ends have been stripped:");
        Console.WriteLine("----------------------------------------------------------------");
        // print out the array of strings
        for( i in strSource )
            Console.WriteLine( StripEndTags( strSource[i] ) );
    }

    private static function StripEndTags( item : String ) : String {
        // try to find a tag at the end of the line using EndsWith
        if (item.Trim().EndsWith(">")) {
            // now search for the opening tag...
            var lastLocation : int = item.LastIndexOf( "</" );
            // remove the identified section, if it is a valid region
            if ( lastLocation >= 0 )
                item =  item.Substring( 0, lastLocation );
        }
        return item;
    }
}
EndsWithTest.Main();


Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile para Smartphone, Windows Mobile para Pocket PC, Xbox 360

.NET Framework y .NET Compact Framework no admiten todas las versiones de cada plataforma. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.

.NET Framework

Compatible con: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Compatible con: 3.5, 2.0, 1.0

XNA Framework

Compatible con: 2.0, 1.0
Mostrar: