Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate string on whole words in .NET C#

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..." 
like image 365
TimS Avatar asked Oct 23 '09 14:10

TimS


People also ask

How do you truncate a string in C#?

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.

How do I limit the length of a string in C#?

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.

How do I truncate a string in VB net?

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.


1 Answers

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)); } 
like image 91
David Avatar answered Sep 28 '22 04:09

David