180 first characters of a line ending with a word

I need to cut the line down.

Let's say we have a string with a length of 500.

I need only the first part - a maximum of 180 characters , ending with the last word before reaching 180. I do not want to cut the line in the middle of the word.

How is this achieved? he should not perform all this well .. this is what happens a couple of times a day, not more.

+4
source share
4 answers

A very simple way is to use this regex:

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

The only problem is that it may contain trailing spaces. To fix this, we can add a little negative look:

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

That should do the trick.

+21
source

How about looking at char 180 and moving backward to find the first char in (lets say a space, comma, exclamation point, etc.) indicating the beginning of the previous word?

+3
source

Conceptially

Make sure the string is longer than 180 characters.

Take the first 180 characters as a substring.

Return what you need using the "LastIndexOf" method to get the length of the string combined with the substring to return the corresponding string.

In code:

  string InString; InString = "Your long string goes here"; if (InString.Length>180) //Check the string length { InString = InString.Substring(0, 180); //Get the first 180 chars InString = InString.Substring(0,InString.LastIndexOf(" ")); //Stop at the last space } 

This will return the correct string; although LastIndexOfAny will allow you to add other characters to the EOL list.

0
source

You just use the usual commands in the string class:

 string short = myStr.Substring(0, 180); int end = short.LastIndexOfAny(new char[] {' ', '\t', '\n'}); //maybe more return short.Substring(0, end); 
0
source

All Articles