Hope somebody has a good idea. I have strings like this:
abcdefg abcde abc
What I need is for them to be trucated to show like this if more than a specified lenght:
abc .. abc .. abc
Is there any simple C# code I can use for this?
If it's longer than a given length n , clip it to length n ( substr or slice ) and add html entity … (…) to the clipped string. function truncate( str, n, useWordBoundary ){ if (str. length <= n) { return str; } const subString = str. slice(0, n-1); // the original check return (useWordBoundary ?
The other way to truncate a string is to use a rsplit() python function. rsplit() function takes the string, a delimiter value to split the string into parts, and it returns a list of words contained in the string split by the provided delimiter.
Make a loop at the end of the string After cutting the string at the proper length, take the end of the string and tie a knot at the very end, then fold the string over and tie a loop, about the same size as the original loop (about 2cm in diameter).
Here is the logic wrapped up in an extension method:
public static string Truncate(this string value, int maxChars) { return value.Length <= maxChars ? value : value.Substring(0, maxChars) + "..."; }
Usage:
var s = "abcdefg"; Console.WriteLine(s.Truncate(3));
All very good answers, but to clean it up just a little, if your strings are sentences, don't break your string in the middle of a word.
private string TruncateForDisplay(this string value, int length) { if (string.IsNullOrEmpty(value)) return string.Empty; var returnValue = value; if (value.Length > length) { var tmp = value.Substring(0, length) ; if (tmp.LastIndexOf(' ') > 0) returnValue = tmp.Substring(0, tmp.LastIndexOf(' ') ) + " ..."; } return returnValue; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With