find the last index of a character in a string in csharp

To find the last index of a character in a string in C#, use the LastIndexOf method of the string class. This method returns the zero-based index of the last occurrence of the specified character in the string, or -1 if the character is not found.

Here's an example:

main.cs
string myString = "hello world";
char myChar = 'o';
int lastIndex = myString.LastIndexOf(myChar);
Console.WriteLine(lastIndex); // Output: 7
141 chars
5 lines

In the example above, we first declare a string variable myString and initialize it with the value "hello world". We then declare a char variable myChar and initialize it with the value 'o'.

Next, we call the LastIndexOf method on myString, passing in myChar as the argument. This returns the zero-based index of the last occurrence of 'o' in the string, which is 7.

Finally, we output the value of lastIndex to the console.

gistlibby LogSnag