Created
December 25, 2016 15:40
-
-
Save heiswayi/d9f941daf91f84ab2fb435c1250929d4 to your computer and use it in GitHub Desktop.
C# Utilities - Substring extensions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Helpers | |
{ | |
internal static class SubstringExtensions | |
{ | |
/// <summary> | |
/// Get string value between [first] a and [last] b. | |
/// </summary> | |
public static string Between(this string value, string a, string b) | |
{ | |
int posA = value.IndexOf(a); | |
int posB = value.LastIndexOf(b); | |
if (posA == -1) | |
{ | |
return ""; | |
} | |
if (posB == -1) | |
{ | |
return ""; | |
} | |
int adjustedPosA = posA + a.Length; | |
if (adjustedPosA >= posB) | |
{ | |
return ""; | |
} | |
return value.Substring(adjustedPosA, posB - adjustedPosA); | |
} | |
/// <summary> | |
/// Get string value after [first] a. | |
/// </summary> | |
public static string Before(this string value, string a) | |
{ | |
int posA = value.IndexOf(a); | |
if (posA == -1) | |
{ | |
return ""; | |
} | |
return value.Substring(0, posA); | |
} | |
/// <summary> | |
/// Get string value after [last] a. | |
/// </summary> | |
public static string After(this string value, string a) | |
{ | |
int posA = value.LastIndexOf(a); | |
if (posA == -1) | |
{ | |
return ""; | |
} | |
int adjustedPosA = posA + a.Length; | |
if (adjustedPosA >= value.Length) | |
{ | |
return ""; | |
} | |
return value.Substring(adjustedPosA); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment