TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# LastIndexOf String Method

These C# examples demonstrate the LastIndexOf and LastIndexOfAny string method. They locate characters from the right.

LastIndexOf searches strings from the right.

It finds the location of the last occurrence of a letter or substring. It requires no explicit for-loop. LastIndexOfAny searches for an array of strings.

Example. We see that the LastIndexOf method acts on instances of the string type. These can be referenced by the string keyword or the actual "String" uppercased class in the base class library.

Tip: There are nine versions of the LastIndexOf method on the string type. They have different implementations.

The method internally searches the instance string from the final character backwards to the first character. If the specified value parameter is located, its index is returned. Otherwise the special value -1 is returned.

Based on:

.NET 4.5

C# program that uses LastIndexOf method

using System;

class Program
{
    static void Main()
    {
	//
	// The string we are searching.
	string value = "Dot Net Perls";
	//
	// Find the last occurrence of N.
	int index1 = value.LastIndexOf('N');
	if (index1 != -1)
	{
	    Console.WriteLine(index1);
	    Console.WriteLine(value.Substring(index1));
	}
	//
	// Find the last occurrence of this string.
	int index2 = value.LastIndexOf("Perls");
	if (index2 != -1)
	{
	    Console.WriteLine(index2);
	    Console.WriteLine(value.Substring(index2));
	}
	//
	// Find the last 'e'.
	// ... This will not find the first 'e'.
	int index3 = value.LastIndexOf('e');
	if (index3 != -1)
	{
	    Console.WriteLine(index3);
	    Console.WriteLine(value.Substring(index3));
	}
	//
	// Find the last occurrence of this string, ignoring the case.
	int index4 = value.LastIndexOf("PERL", StringComparison.OrdinalIgnoreCase);
	if (index4 != -1)
	{
	    Console.WriteLine(index4);
	    Console.WriteLine(value.Substring(index4));
	}
    }
}

Output

4
Net Perls
8
Perls
9
erls
8
Perls

In Visual Studio you can select overloads of LastIndexOf by typing the period and scrolling through the IntelliSense popup. In the method calls here, the starting index is the final character index and the count is the string length.

OverloadVisual Studio

Tip: When you specify the startIndex, specify the position where searching begins, not the first character in the range you are searching.

Next, the program uses the LastIndexOf method to do a case-insensitive string search. This option is only available with the string type overloads of the LastIndexOf method. The char-based overloads do not offer this option.

The StringComparison.OrdinalIgnoreCase value is an enumerated constant that specifies that you want to treat characters as number values (ordinals) and not culture-specific values. Ordinal searches are faster.

LastIndexOfAny searches for multiple characters in reverse. It returns the final position of any of a set of characters. This method provides this string functionality in the C# language.

Tip: When you call LastIndexOfAny, you must provide a character array. One way of doing this is shown in the example.

Here: The example searches for the first instance of a 'd' or 'b' character starting from the end of the string.

Char Array

And: The position returned is 5, which is the final 'd' in the input string. The search terminates when something is found.

C# program that uses LastIndexOfAny method

using System;

class Program
{
    static void Main()
    {
	// Input string.
	const string value = "ccbbddee";
	// Search for last of any of these characters.
	int index = value.LastIndexOfAny(new char[] { 'd', 'b' });
	Console.WriteLine(index);
    }
}

Output

5

Cache. The performance of LastIndexOfAny is not ideal. If you want to improve it, one thing you can do is store the character array argument in a field—static or instance—and then use a reference to that cache as the argument.

Note: This will avoid an object creation on every call. And reducing object creations reduces memory pressure and garbage collections.

Discussion. The IndexOf methods are similar to the LastIndexOf method. They search from the first positions forward, not the last positions backwards. The IndexOf methods are more commonly used.

IndexOf

Summary. LastIndexOf and LastIndexOfAny locate strings from the right side. LastIndexOf can be used with a string type argument. But it can be called with a char type argument—and this influences performance.

Char


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf