Skip to content

Instantly share code, notes, and snippets.

@nickalbrecht
Created October 7, 2023 00:45
Show Gist options
  • Save nickalbrecht/68a4aa6916f1bef05d1a854e0d1f89c4 to your computer and use it in GitHub Desktop.
Save nickalbrecht/68a4aa6916f1bef05d1a854e0d1f89c4 to your computer and use it in GitHub Desktop.
A method for truncating a long string using ellipse. You can prefer to truncate the end of the string, or cut a chunk out of the middle and keep the start and end of the string. It will also shift the cutoff point slightly to the closest space/punctuation for aesthetics
public enum EllipseStyle { End, Middle };
public static string EllipsizeString(this string text, int? maxLength, EllipseStyle ellipseStyle)
{
if(string.IsNullOrEmpty(text))
return null;
const string ellipsis = "...";
var preferredCharacters = new[] { ' ', ',', '.', ';', ':', '?', '!' };
string truncatedString = null;
if (text?.Length > maxLength) {
switch (ellipseStyle) {
case EllipseStyle.End:
//Trucates the end of the string string using the MaxLength (minus lenth of the ellipsis), but will shift to the closest non word character for aesthetics
var prelimTruncationPoint = maxLength.Value - ellipsis.Length;
var truncationPoint = text.LastIndexOfAny(preferredCharacters, prelimTruncationPoint);
if (truncationPoint == -1) {
truncationPoint = prelimTruncationPoint;
}
truncatedString = $"{text[..(truncationPoint)]}{ellipsis}";
break;
case EllipseStyle.Middle:
var threeQuartersOfMaxLength = (int)Math.Round(maxLength.Value * 0.75, MidpointRounding.ToZero); //75% of the MaxLength (rounded down, so we will never be more than MaxLength))
var prelimStartEllipsisPoint = threeQuartersOfMaxLength - ellipsis.Length; //Index to stop at to for getting our first segment
var prelimEndEllipsisPoint = text.Length - (maxLength.Value - threeQuartersOfMaxLength); //Index to start from to get our second sesgment
var ellipsisStartPoint = text.LastIndexOfAny(preferredCharacters, prelimStartEllipsisPoint); //Gets the last occurange of one of the preferred characters, up until we hit the prelimStartEllipsisPoint index
var ellipsisEndPoint = text.IndexOfAny(preferredCharacters, prelimEndEllipsisPoint); //Gets the first occurance of one of the preferred characters, starting from the prelimEndEllipsisPoint index
if (ellipsisStartPoint == -1) { //In case there are none of the characters we want within the first segment
ellipsisStartPoint = prelimStartEllipsisPoint;
}
if (ellipsisEndPoint == -1) { //In case there are none of the characters we want within last segment of the string
ellipsisEndPoint = prelimEndEllipsisPoint;
}
truncatedString = $"{text[..(ellipsisStartPoint)]}{ellipsis}{text[(ellipsisEndPoint)..]}";
break;
}
}
else {
truncatedString = text;
}
return truncatedString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment