Search code examples
c#splittrimindexoutofrangeexception

mysterious IndexOutOfRangeException


Visual Studio throws an IndexOutOfRangeException inside this function:

public static string ExtractString(string path, string startString, char endChar)
{
    string content = File.ReadAllText(path);

    /*at this line*/return content.Split(new string[] { startString }, StringSplitOptions.None)[1].Split(endChar)[0].Trim();
}

Any idea what I am doing wrong here?


Solution

  • That's a strange way of doing it, but I tested with some sample input of my own and it works okay under expected circumstances.

    The problem occurs when startString is not found, because the resulting array from the first string.Split will contain a single element (the original input string). When you attempt to split the 2nd element on endChar, there is no 2nd element to find, and that is your exception.

    I'm sure there are more elegant ways to do this, but this will do the job, returning null if either startString or endChar cannot be found:

    public static string ExtractString(string content, string startString, char endChar)
    {
        int i, j;
    
        i = content.IndexOf(startString);
    
        if (i == -1)
            return null;
        else
            i += startString.Length; // Start at char after startString
    
        j = content.IndexOf(endChar);
    
        if (j == -1)
            return null;
    
        return content.Substring(i, j - i);
    }