views:

101

answers:

4

i have a text file with string "abcdef"

I want to search for the string "abc" in my test file ... and print the next two character for abc ..here it is "de".

how i could accomplish ? which class and function?

+3  A: 

Read you file line by line an use something like:

string line = "";

if line.Contains("abc") { 
    // do
}

Or you could use regular expressions.

Match match = Regex.Match(line, "REGEXPRESSION_HERE");
thelost
you want to do `Match( content, "abc(..)" );` or something like that
tanascius
+2  A: 

Try this:

string s = "abcde";
int index = s.IndexOf("abc");
if (index > -1 && index < s.Length - 4)
    Console.WriteLine(s.SubString(index + 3, 2));

Update: tanascius noted a bug. I fixed it.

Steven
@tanascius: fixed.
Steven
+1  A: 

In order to print all instances you can use the following code:

int index = 0;

while ( (index = s.IndexOf("abc", index)) != -1 )
{
   Console.WriteLine(s.Substring(index + 3, 2));
}

This code assumes there will always be two characters after the string instance.

Elisha
A: 

I think this is a more clear example:

    // Find the full path of our document
    System.IO.FileInfo ExecutableFileInfo = new System.IO.FileInfo(System.Reflection.Assembly.GetEntryAssembly().Location);            
    string path = System.IO.Path.Combine(ExecutableFileInfo.DirectoryName, "MyTextFile.txt");

    // Read the content of the file
    string content = String.Empty;
    using (StreamReader reader = new StreamReader(path))
    {
        content = reader.ReadToEnd();
    }

    // Find the pattern "abc"
    int index = -1; //First char index in the file is 0
    index = content.IndexOf("abc");

    // Outputs the next two caracters
    // [!] We need to validate if we are at the end of the text
    if ((index >= 0) && (index < content.Length - 4))
    {
        Console.WriteLine(content.Substring(index + 3, 2));
    }

Note that this only works for the first coincidence. I dunno if you want to show all the coincidences.

Javier Morillo