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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With