C# - String: find last occurence before...

By , 8/19/2015
(0 ratings)
The string type has many methods to find out indexes of substrings. This method extends the repertoire with a method that finds the last occurence of a substring before a given index.
This method is implemented as an Extension method and is compatible with PCLs.

Required Namespace
System
Translate to VB
/// <summary>
/// Reports the last zero based index of the occurence of the specified string before the given index.
/// </summary>
/// <param name="s">The string to be searched.</param>
/// <param name="value">The string to find.</param>
/// <param name="untilIndex">The last possible index that can be returned.</param>
/// <returns>A zero-based index of the last occurence of <paramref name="value"/> in <paramref name="s"/> before <paramref name="untilIndex"/>.</returns>
public static int LastIndexUntil(this string s, string value, int untilIndex)
{
    if (s == null)
        throw new ArgumentNullException("s", "s cannot be null");
    if (value == null)
        throw new ArgumentNullException("value", "value cannot be null");
    if (untilIndex < 0)
        throw new ArgumentOutOfRangeException("untilIndex", "untilIndex cannot be negative");

    //for the case that untilIndex is greater than s.Length or value does not fit behind untilIndex into s
    untilIndex = Math.Min(untilIndex, s.Length - value.Length);

    if (value == "")
    {
        if (s.Length == 0)
            return 0;
        else
            return untilIndex;
    }

    var chars = s.ToCharArray();
    var c = value.ToCharArray();

    for (int i = untilIndex; i >= 0; --i)
    {
        if (chars[i] == c[0])
        {
            bool found = true;
            for (int j = 1; j < c.Length; ++j)
            {
                if (chars[i + j] != c[j])
                {
                    found = false;
                    break;
                }
            }
            if (found)
                return i;
        }
    }
    return -1;
}
Tagged with String, Index, Analyze, IndexOf, Analyze, Parse, Until.

Comments

 

Log in, to comment!