Return to Snippet

Revision: 18579
at October 2, 2009 12:23 by jasonseney


Initial Code
public static string Truncate(string sourceText, string ellipsis, int min, int max)
{
	//If text is shorter than preview length
	if (sourceText.Length <= max)
	{
		return sourceText; //@RETURN break out early if too short
	}

	//Grab the char at the last position allowed
	char cutOffChar = sourceText[max];

	int lastPosition = max;

	//While the last char isn't a space, cut back until we hit a space or minimum
	while (cutOffChar != ' ' && lastPosition > min)
	{
		lastPosition--;
		cutOffChar = sourceText[lastPosition];
	}

	//Crop text and add some dots
	string outText = sourceText.Substring(0, lastPosition);
	outText += ellipsis;

	return outText;
}

Initial URL

                                

Initial Description

                                

Initial Title
C# Truncate String Text

Initial Tags
c

Initial Language
C#