Get context for search string in text in C#

Posted by soundslike on Stack Overflow See other posts from Stack Overflow or by soundslike
Published on 2009-05-31T14:49:53Z Indexed on 2010/04/15 23:03 UTC
Read the original article Hit count: 205

Filed under:
|
|

Given a string text which contains newline there is a search keyword which matches an item within the text.

How do I implement the following in C#:

searchIdx = search index (starting with 0, then 1, etc. for each successive call to GetSearchContext. Initially start with 0.

contextsTxt = string data to search in

searchTxt = keyword to search for in contextsTxt

numLines = number of lines to return surrounding the searchTxt found (ie. 1 = the line the searchTxt is found on, 2 = the line the searchTxt is found on, 3 = the line above the searchTxt is found on, the line the searchTxt is found on, and the line below the searchTxt is found on)

returns the "context" based on the parameters

string GetSearchContext(int searchIdx, string contentsTxt, string searchTxt, int numLines);

If there's a better function interface to accomplish this feel free to suggest that as well.

I tried the following but doesn'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;
	}

© Stack Overflow or respective owner

Related posts about search

Related posts about context