Search code examples
c#stringssisstring-parsing

search through the string from last and find the second occurrence of a string


I have one requirement to search the string and need to find second occurrence of the same string from last(ascending order) and have to read it from that search string to last in a file.

Example String:

START BATCH;Cube check SUCCESS;Cube Check Status Time;2/22/2017 5:54:02AM; Entered try;Web check Passed;STOP BATCH;START BATCH;Cube check SUCCESS;Cube Check Status Time  

from this semicolon separated string i need to search the second re- occurring string START BATCH from the last(down to up) then from that string i need to store that whole sub-string into string array.

Earlier i am able to get the string through LastIndexof method. But this time i need to get the second occurrence of the same string.
Your help is much appreciated.


Solution

  • You can use the LastIndexOf() version that takes a startIndex argument:

    public int FindSecondLastIndex(string input, string search)
    {
        int lastIndex = input.LastIndexOf(search);
        if (lastIndex <= 0) return -1;
        return input.LastIndexOf(search, lastIndex - 1);
    }
    

    and use it:

    string input = "START BATCH;Cube check SUCCESS;Cube Check Status Time;2/22/2017 5:54:02AM; Entered try;Web check Passed;STOP BATCH;START BATCH;Cube check SUCCESS;Cube Check Status Time"
    string search = "START BATCH";
    
    Console.WriteLine(FindSecondLastIndex(input, search));
    

    Output: 0.


    You can improve performance a little bit by checking the length:

    if (lastIndex < search.Length) return -1;
    return input.LastIndexOf(search, lastIndex - search.Length);
    

    And probably implement it as extension for string:

    public static class StringExtension
    {
        public static int SecondLastIndexOf(this string input, string search)
        { ... }
    }
    

    so you can use it like

    var index = input.SecondLastIndexOf(search);