Given a string text containing a new line, there is a search keyword that matches an element in the text.
How to implement the following in C #:
searchIdx = search index (starting at 0, then 1, etc. for each subsequent call to GetSearchContext. First, start at 0.
contextsTxt = string data to search in
searchTxt = search keyword in contextsTxt
numLines = the number of lines returned by the environment of the searchTxt found (i.e. 1 = the line on which searchTxt was found, 2 = the line on which searchTxt was found, 3 = the line above the search tag is in the line, the searchTxt line is, and line found under search text)
returns a "context" based on parameters
string GetSearchContext (int searchIdx, string contentsTxt, string searchTxt, int numLines);
If there is a better functional interface to accomplish this, feel free to suggest this as well.
I tried the following, but didn't seem to work properly all the time:
private string GetSearchContext(string contentValue, string search, int numLines) { int searchIdx = contentValue.IndexOf(search); int startIdx = 0; int lastIdx = 0; while (startIdx != -1 && (startIdx = contentValue.IndexOf('\n', startIdx+1)) < searchIdx) { lastIdx = startIdx; } startIdx = lastIdx; if (startIdx < 0) startIdx = 0; int endIdx = searchIdx; int lineCnt = 0; while (endIdx != -1 && lineCnt++ < numLines) { endIdx = contentValue.IndexOf('\n', endIdx + 1); } if (endIdx == -1 || endIdx > contentValue.Length - 1) endIdx = contentValue.Length - 1; string lines = contentValue.Substring(startIdx, endIdx - startIdx + 1); if (lines[0] == '\n') lines = lines.Substring(1); if (lines[lines.Length - 1] == '\n') { lines = lines.Substring(0, lines.Length - 1); } if (lines[lines.Length - 1] == '\r') { lines = lines.Substring(0, lines.Length - 1); } return lines; }