Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

180 first characters of a string ending with a word

Tags:

c#

asp.net

I need to shorten a string down..

Lets say we have a string with the length 500.

I only want the first part of it - max 180 characters, ending with the last word before reaching the 180. I don't want to cut the string short in the middle of a word.

How is this achived? it does not have to perform all that well.. it is something that happens a couple of times a day, not more.

like image 720
The real napster Avatar asked Nov 29 '22 20:11

The real napster


1 Answers

A really easy way is by using this regex:

string trimmed = Regex.Match(input,@"^.{1,180}\b").Value;

The only problem with that one is that it could contain trailing whitespace. To fix that, we can add a little negative look-behind:

string trimmed = Regex.Match(input,@"^.{1,180}\b(?<!\s)").Value;

That should do the trick.

like image 84
Philippe Leybaert Avatar answered Dec 10 '22 06:12

Philippe Leybaert