A Sub-string Extractor with Specific Keywords Parameter Implementation in C#
I tend to have the &quot;error handling&quot; code at the beginning of the method, which usually makes the rest of the method more simple.
private static string GetTargetString(string input, string startKeyword, string endKeyword, StringComparison comparer)
{
    if (!string.IsNullOrEmpty(startKeyword) &amp;&amp; input.IndexOf(startKeyword, comparer) &lt; 0) return &quot;&quot;;
    if (!string.IsNullOrEmpty(endKeyword) &amp;&amp; input.IndexOf(endKeyword, comparer) &lt; 0) return &quot;&quot;;

    var startIndex = string.IsNullOrEmpty(startKeyword)
        ? 0
        : input.IndexOf(startKeyword, comparer) + startKeyword.Length;

    var endIndex = string.IsNullOrEmpty(endKeyword) 
        ? input.Length 
        : input.IndexOf(endKeyword, comparer);

    if (startIndex &lt; 0 || endIndex &lt; 0 || startIndex &gt;= endIndex) return &quot;&quot;;

    return input.Substring(startIndex, endIndex - startIndex).Trim();
}