[.net] searching in C#
hi everyone,
This is the first time i am coming here so here it goes , my problem is that i want to search for a word in a file. I have created the FileStream did the seeking and reading of the file. i have also done the byte, character array. What i need to do now to search for word in that character array ? how do i do that?? .any idea anyone!.
Thank you.
The most obvious (and not the most efficient by any means) is to just read the whole file into a string and then use String.IndexOf. The best way to get a file into a string is to use a StreamReader:
string s;using(StreamReader reader = new StreamReader(@"C:\file.txt")){ s = reader.ReadToEnd();}int index = s.IndexOf(wordToSearchFor);if ( index >= 0 ){ // word was found}
A slightly modified version of the code above will get you indices of all the occurences of your word in a file.
string s;using(StreamReader reader = new StreamReader(@"C:\file.txt")){ s = reader.ReadToEnd();}ArrayList startIndices = new ArrayList();for(int i = 0; i < s.Length; ++i){ int index = s.IndexOf(wordToSearchFor, i); if(index > -1){ startIndices.Add(index); i += index + wordToSearchFor.Length; }}
if the file is rather big you might want to consider using a circular buffer or something rather then loading the whole file in to memory at once.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement