[Q] How to truncate a string with more than 5 characters by adding an ellipsis to its end?
[Example] "1234567" -> "12345..."
[Answer]
private string Truncate(string s)
{
return new string(s.Take(5).ToArray()) + "...";
}
Finally, this link has more explanation on string truncate in C#. Thank you all. Please, like us on Facebook!
6 comments:
Very good. I never thought you could use linq to manipulate strings. Thank you
Actually, a C# string is an array of Char, therefore, an IEnumerable. Since LINQ is simply a bunch of methos build on IEnumerable. Take a look at: http://msdn.microsoft.com/en-us/library/bb503062.aspx
Why the .ToArray after the on the string truncate method?
the constructor of the class string receives an array of Char...
this string truncate method uses LINQ to get a sub array of Chars. Then, the truncate method passes the new Char array to the string constructor.
great string truncate approach in C#. Thankx
Post a Comment