Skip to content

Instantly share code, notes, and snippets.

@rymoore99
Last active August 29, 2015 13:56
Show Gist options
  • Save rymoore99/9091263 to your computer and use it in GitHub Desktop.
Save rymoore99/9091263 to your computer and use it in GitHub Desktop.
Extension method to truncate a string to the last space after a specified length
public static class StringExtension
{
public static string SplitByCaps(this string value)
{
var r = new Regex(@"
(?<=[A-Z])(?=[A-Z][a-z]) |
(?<=[^A-Z])(?=[A-Z]) |
(?<=[A-Za-z])(?=[^A-Za-z])", RegexOptions.IgnorePatternWhitespace);
return r.Replace(value, " ");
}
public static string ToTitleCase(this string value) {
return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(value.ToLower());
}
public static string TruncateToLastSpace(this string valueToTruncate, int maxLength)
{
if (valueToTruncate == null)
{
return string.Empty;
}
if (valueToTruncate.Length <= maxLength)
{
return valueToTruncate;
}
string retValue = valueToTruncate;
int lastSpaceIndex = retValue.LastIndexOf(" ",
maxLength, StringComparison.CurrentCultureIgnoreCase);
if (lastSpaceIndex > -1)
{
retValue = retValue.Remove(lastSpaceIndex);
}
if (retValue.Length < valueToTruncate.Length)
{
retValue += "&hellip;";
}
return retValue;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment