Tuesday, May 21, 2013

Quick challenge #2: how to truncate a string in C# and keep word boundaries (do not split a word in two)

[Q] How to truncate a string in C# with more than 10 characters and keep word boundaries (do not split a word in two)?

[Examples] "Good morning test." -> "Good morni..." (wrong), "Good morning..." (correct)

       

       [Answer]

private static string Truncate(string s)

        {

            return new string(s.Take(10).ToArray()) + new string(s.Skip(10).TakeWhile(c => !Char.IsWhiteSpace(c) && !Char.IsPunctuation(c)).ToArray()) + "...";

        }

We are assuming here that punctuation symbols and whitespaces are word boundaries. Therefore, the code takes 10 characters and, after that, it continues taking characters up to the first word boundary. This is a super simple implementation that hides practical problems, but it works for learning LINQ and C# :)

If you liked this post, please, help us! like us on facebook page!! Take a look at the other posts too. Thanks a lot!

Follow us on Twitter: @TapiocaCom

Like us on facebook: http://www.facebook.com/Tapiocacom

 

 

No comments:

Post a Comment