Created
January 26, 2012 13:56
-
-
Save leegould/1682866 to your computer and use it in GitHub Desktop.
string extension method - Chomp
This file contains 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
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