Friday, May 10, 2013

Quick challenge C#: how to truncate a string with more than 10 characters by adding an ellipsis to its end?

[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:

Anonymous said...

Very good. I never thought you could use linq to manipulate strings. Thank you

Unknown said...

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

Anonymous said...

Why the .ToArray after the on the string truncate method?

Unknown said...

the constructor of the class string receives an array of Char...

Unknown said...

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.

Anonymous said...

great string truncate approach in C#. Thankx

Post a Comment