Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I truncate my strings with a "..." if they are too long?

Tags:

string

c#

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?

like image 879
Melony Avatar asked Jul 17 '11 15:07

Melony


People also ask

How do you trim a long string?

If it's longer than a given length n , clip it to length n ( substr or slice ) and add html entity &hellip; (…) 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 ?

How do you truncate a long string in python?

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.

How do you shorten a string?

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).


2 Answers

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)); 
like image 103
Bryan Watts Avatar answered Nov 16 '22 22:11

Bryan Watts


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; } 
like image 42
JStevens Avatar answered Nov 16 '22 23:11

JStevens