Jump to content
  • Advertisement
Sign in to follow this  
omerehman

[.net] searching in C#

This topic is 4828 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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
}


Share this post


Link to post
Share on other sites
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;
}
}

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!