I’m trying to create an “snippet” from a paragraph. I have a long paragraph of text with a word hilighted in the middle. I want to get the line containing the word before that line and the line after that line.
I have the following piece of information:
- The text (in a string)
- The lines are deliminated by a NEWLINE character
\n - I have the index into the string of the text I want to hilight
A couple other criteria:
- If my word falls on first line of the paragraph, it should show the 1st 3 lines
- If my word falls on the last line of the paragraph, it should show the last 3 lines
- Should show the entire paragraph in the degenative cases (the paragraph only has 1 or 2 lines)
Here’s an example:
This is the 1st line of CAT text in the paragraph
This is the 2nd line of BIRD text in the paragraph
This is the 3rd line of MOUSE text in the paragraph
This is the 4th line of DOG text in the paragraph
This is the 5th line of RABBIT text in the paragraph
Example, if my index points to BIRD, it should show lines 1, 2, & 3 as one complete string like this:
This is the 1st line of CAT text in the paragraph
This is the 2nd line of BIRD text in the paragraph
This is the 3rd line of MOUSE text in the paragraph
If my index points to DOG, it should show lines 3, 4, & 5 as one complete string like this:
This is the 3rd line of MOUSE text in the paragraph
This is the 4th line of DOG text in the paragraph
This is the 5th line of RABBIT text in the paragraph
etc.
Anybody want to help tackle this?
Using the LINQ extension methods to get the right strings:
This can of course be optimized a bit by quitting the for loop as soon as the index has been found, and probably a number of other things. You can probably even LINQify so you never need to actually store that extra array, but I can’t think of a good way to do that right now.
An alternative for the checks on position could be something like
position = Math.Max(0,Math.Min(position, lines.Count() - 3));– which would handle both of them at once.