I am trying to truncate some long text in C#, but I don't want my string to be cut off part way through a word. Does anyone have a function that I can use to truncate my string at the end of a word?
E.g:
"This was a long string..."
Not:
"This was a long st..."
Substring() method in C#. Then we created the extension method Truncate() that takes the desired length and truncates the string to the desired length. If the string variable is null or empty, the Truncate() method returns the string.
Strings in C# are immutable and in some sense it means that they are fixed-size. However you cannot constrain a string variable to only accept n-character strings. If you define a string variable, it can be assigned any string.
public static string Truncate(this string text, int maxLength, string suffix = "...") { string str = text; if (maxLength > 0) { int length = maxLength - suffix. Length; if (length <= 0) { return str; } if ((text != null) && (text. Length > maxLength)) { return (text.
Try the following. It is pretty rudimentary. Just finds the first space starting at the desired length.
public static string TruncateAtWord(this string value, int length) { if (value == null || value.Length < length || value.IndexOf(" ", length) == -1) return value; return value.Substring(0, value.IndexOf(" ", length)); }
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