[.net] searching in C#

Started by
3 comments, last by paulecoyote 18 years, 7 months ago
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.
Advertisement
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}
--AnkhSVN - A Visual Studio .NET Addin for the Subversion version control system.[Project site] [IRC channel] [Blog]
Thankx.
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;   }}

[Formerly "capn_midnight". See some of my projects. Find me on twitter tumblr G+ Github.]

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.
Anything posted is personal opinion which does not in anyway reflect or represent my employer. Any code and opinion is expressed “as is” and used at your own risk – it does not constitute a legal relationship of any kind.

This topic is closed to new replies.

Advertisement