zaterdag 24 mei 2008

A System.String extension method Substring

kick it on DotNetKicks.com

Almost every time I use String.Substring() I have to do a few IndexOf calls to find the "startIndex" en "length" to use. This includes declaring local variables and verifying that the index found is not smaller than zero. This extension method solves these issues. (Long live C# 3.0!)


public static string Substring(this String str, string startText, string endText, StringComparison comparisonType)
{
string lsResult = "";
Int32 liStartPos = str.IndexOf(startText, comparisonType);
if (liStartPos >= 0) {
liStartPos = liStartPos + startText.Length;
Int32 liEndPos = str.IndexOf(endText, liStartPos, comparisonType);
if (liEndPos >= 0) {
lsResult = str.Substring(liStartPos, liEndPos - liStartPos);
}
}
return lsResult;
}

public static string Substring(this String str, string startText, string endText)
{
string lsResult = "";
Int32 liStartPos = str.IndexOf(startText, StringComparison.CurrentCulture);
if (liStartPos >= 0) {
liStartPos = liStartPos + startText.Length;
Int32 liEndPos = str.IndexOf(endText, liStartPos, StringComparison.CurrentCulture);
if (liEndPos >= 0) {
lsResult = str.Substring(liStartPos, liEndPos - liStartPos);
}
}
return lsResult;
}
I wasn't sure if overloading existing methods was alowed, but it works.

kick it on DotNetKicks.com

Geen opmerkingen: