Skip to content

Instantly share code, notes, and snippets.

@KristofferK
Created February 11, 2018 12:19
Show Gist options
  • Select an option

  • Save KristofferK/263de5b8e0c9b313b748abb7ecaeecb7 to your computer and use it in GitHub Desktop.

Select an option

Save KristofferK/263de5b8e0c9b313b748abb7ecaeecb7 to your computer and use it in GitHub Desktop.
Gets the substring inbetween two other substrings. InBetween("Hello beautiful world", "Hello ", " world") => "beautiful"
namespace Utils
{
public static class Util
{
public static string InBetween(string haystack, string afterThis, string beforeThis)
{
return InBetween(haystack, afterThis, beforeThis, 1, 0);
}
public static string InBetween(string haystack, string afterThis, string beforeThis,
int afterIndex, int beforeIndex, bool includeAfterAndBefore = false)
{
if (haystack == null) return null;
if (haystack.Contains(afterThis))
{
var split = Split(haystack, afterThis);
if (split.Length > afterIndex)
{
string rv = split[afterIndex];
if (rv.Contains(beforeThis))
{
split = Split(rv, beforeThis);
if (split.Length > beforeIndex)
{
rv = split[beforeIndex];
if (includeAfterAndBefore)
{
rv = $"{afterThis}{rv}{beforeThis}";
}
return rv;
}
}
}
}
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment