Friday, July 31, 2009

Search function using a keyword on a text file in C#?

Just want to know if its possible to do a search function using a keyword on a text file in C#.





For example,


lets just call the text file test.txt, and the content of the file is





BOOK xxx,yyy,zzz


AUTHOR xy, yx, yy


YEAR 1999,1929,2009


PRICE 99,77,195


COMMENT very very good


MAGAZINE asd,avacs,etc


COVER hard, soft








So BOOK is the keyword and AUTHOR, YEAR, PRICE and COMMENT are sub-keywords marked by spaces before the words(likewise for MAGAZINE and COVER).


What I'm after is when user type in keyword BOOK, it returns the whole 5 lines starting from BOOK to COMMENT. And when user types in PRICE, it returns only 1 line(PRICE 99,77,195).





The output could be just a display in the console.





TextReader tr = new StreamReader("test.txt");


String contents = tr.ReadToEnd();


String keyword = "BOOK";





Could anyone help me with the searching part? dont worry about indentations for now, just a quick search for the word BOOK on "contents" would be superb.

Search function using a keyword on a text file in C#?
Use the method IndexOf





if (contens.IndexOf(keyword) %26gt;= 0)


{


// string in array


}


No comments:

Post a Comment