This post will help help you to truncate the given string to a limited word. Just pass the original string and world limit as an input parameter and it will return the truncated string.
This code checks every word of string and count the words in string and if it reaches the maximum word limit, it just returns the limited word string.
public static string truncate(string originalInput, int wordsLimit)
{
if (originalInput != null && originalInput != "")
{
StringBuilder output = new StringBuilder(originalInput.Length);
StringBuilder input = new StringBuilder(originalInput);
int words = 0;
bool lastwasWS = true;
int count = 0;
do
{
if (char.IsWhiteSpace(input[count]))
{
lastwasWS = true;
}
else
{
if (lastwasWS) words++;
lastwasWS = false;
}
output.Append(input[count]);
count++;
} while ((words < wordsLimit || lastwasWS == false) && count < originalInput.Length);
return output.ToString();
}
else
{
return string.Empty;
}
}
0 comments:
Post a Comment