user979331
user979331

Reputation: 11851

ASP.NET Substring cutting off sentence

I have a paragraph of text that I get from a database, I only want the first 175 characters, which I am able to get via this:

@item.post.Substring(0, Math.Min(item.post.Length, 175))

However, it cuts off my paragraph, is it possible to get grab the paragraph unto 175 characters, however don’t grab anything after the last period so my paragraph looks like this…

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nunc metus, varius vel mi eu, sagittis hendrerit sem. Sed sit amet lectus in eros vulputate lacinia.

instead of this

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nunc metus, varius vel mi eu, sagittis hendrerit sem. Sed sit amet lectus in eros vulputate lacinia. Vestibulum

I guess my question is, after I get the first 175 characters, how would I grab the text to the last period?

Upvotes: 0

Views: 193

Answers (1)

Aydin
Aydin

Reputation: 15284

Use this

@item.post.Substring(0, @item.post.Substring(0, 175).LastIndexOf('.')+1);

Though this will fail if the sentence doesn't contain any periods, so you may want to do some tweaking before using it. (checking that the period exists)

Upvotes: 1

Related Questions