Jan 30 2006

Extend String.IndexOf() & String.LastIndexOf() Methods

Category:Bil@l @ 09:31

I have always found a limitation in the string.IndexOf() and string.LastIndexOf() methods in a sense that, you can either get the position of the first occurrence or the last occurence of a certain value within a given string.

What if we want to get the position of a value at the second occurrence or third or fourth, etc ...?

The solution is simple, look at the following C# function:

public int PositionOf(string strString, string value, int occurrence)
{
    int num1 = -1;

    for(int i=0; i<occurrence; i++)
    {
        num1 = strString.IndexOf(value,num1+1);
    }

    return (num1);

What this simple function does, is to return the position of a value within a given string at any occurrence of choice.

A great thanks to my colleague Ms. Samar Khayat who shared her ideas while working on this function in our office work.

HTH,

Regards

Tags:

Comments are closed