Find The Position Of The Last Occurrence Of A Substring In A String In C#
Code snippet for how to Find The Position Of The Last Occurrence Of A Substring In A String In C# with sample and detail explanation
Finding the position of the last occurrence of a substring in a string can be quite handy, especially when parsing or analyzing text. In this article, we’ll look at how to accomplish this in the C# programming language.
Code snippet for Finding The Position of The Last Occurrence Of A Substring In A String
Below is an example code snippet that demonstrates how to find the index of the last occurrence of a substring.
class Program
{
static void Main()
{
string str = "Hello, this is an example string. This string is for example purposes.";
string subStr = "example";
int lastIndex = str.LastIndexOf(subStr);
Console.WriteLine("Last occurrence of \"{0}\" in \"{1}\" is at index: {2}", subStr, str, lastIndex);
}
}
Code Explanation for Finding The Position of The Last Occurrence Of A Substring In A String
The implementation of this feature in C# is straightforward thanks to the LastIndexOf
method that’s part of the String
class in .NET.
Step 1: We declare and initialize our main string str
and the substring subStr
that we want to find. Here we’ve used “example” as the substring we’re looking for in a sentence.
string str = "Hello, this is an example string. This string is for example purposes.";
string subStr = "example";
Step 2: Next, we call the LastIndexOf
method on our main string, passing the substring as the argument. This method will return the starting index of the last occurrence of the given substring. If the substring is not found, it will return -1.
int lastIndex = str.LastIndexOf(subStr);
Step 3: Finally, we print the result. The output will show the position of the last occurrence of the substring in the string.
Console.WriteLine("Last occurrence of \"{0}\" in \"{1}\" is at index: {2}", subStr, str, lastIndex);
That’s all it takes to find the position of the last occurrence of a substring in a string in C#. Using LastIndexOf
, you can easily locate the last presence of any substring in your string, making it a great tool for text parsing and analysis.