Skip to content

Instantly share code, notes, and snippets.

@leegould
Created January 26, 2012 13:56
Show Gist options
  • Save leegould/1682866 to your computer and use it in GitHub Desktop.
Save leegould/1682866 to your computer and use it in GitHub Desktop.
string extension method - Chomp
using System.Text.RegularExpressions;
namespace Extensions
{
public static class StringExtensions
{
/// <summary>
/// Small function to try and strip a bunch of text down to the first
/// number of words, or just return the original string if it is less
/// than that number of words.
/// </summary>
/// <param name="str">string to search (the object being called on)</param>
/// <param name="wordcount">How many words to include</param>
/// <param name="afterstring">The string to append to the chopped down string (i.e. "...")</param>
/// <returns>The chomp'ed string, with the afterstring appended.</returns>
public static string ChompString(this string str, int wordcount, string afterstring)
{
// Start of string (\A) any spaces (\s*), any character except space (\S) one or more times,
// then any space zero or more times, matched for wordcount.
Regex regex = new Regex(@"\A(\s*(\S+)\s+){" + wordcount + "}", RegexOptions.Compiled);
Match match = regex.Match(str);
return match.Success ? match.Value + afterstring : str;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment