Skip to content

Instantly share code, notes, and snippets.

@built
Created January 12, 2012 20:02
Show Gist options
  • Save built/1602769 to your computer and use it in GitHub Desktop.
Save built/1602769 to your computer and use it in GitHub Desktop.
Reworked the sample I saw floating around to be closer to how I'd write it. Did not fix bugs.
// Two tips from Brian Kernighan:
// 1. Say what you mean, simply and directly.
// 14. Use symbolic constants for magic numbers. (Applies to chars and strings too.)
//
namespace System
{
public static class SentenceParser
{
protected char BLANK = ' ';
public static string TrimSentence(this string @input_string, int length)
{
if (BadInput(length, @input_string)) return string.Empty;
if (length >= @input_string.Length) return @input_string;
if (NextCharacter(@input_string, length) == BLANK) return NormallyParsedString(length, @input_string);
return SentenceEndingAfterPreviousWord(@input_string, length);
}
private static string NormallyParsedString(int length, string @string)
{
return @string.Substring(0, length);
}
private static bool BadInput(int length, string @string)
{
return length <= 0 || string.IsNullOrEmpty(@string);
}
public static string TrimSentence(this string @input_string, int length, bool useEllipsis)
{
return TrimSentence(@input_string, length) + OptionalEllipsis(useEllipsis, @input_string, length);
}
private static bool OptionalEllipsis(bool addEllipsis, string @string, int length)
{
return (addEllipsis && @string.Length > length && length > 0 ) ? "..." : string.Empty;
}
private static string SentenceEndingAfterPreviousWord(string @string, int length)
{
var lastSpaceIndex = @string.Substring(0, length).LastIndexOf(" ");
return @string.Substring(0, lastSpaceIndex);
}
private static char NextCharacter(string @string, int length)
{
return @string[length + 1];
}
}
}
@built
Copy link
Author

built commented Jan 12, 2012

Pondering the names for NormallyParsedString and SentenceEndingAfterPreviousWord cost me the most mental burden here, so I decided not to rename them. I removed articles (the, an, etc.) where possible to reduce noise.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment