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?

1
  • The next two characters can't be linebreaks? So your pattern abd is always within one line followed by two chars in the same line?
    – tanascius
    Mar 10, 2010 at 14:32

4 Answers 4

3

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.

0
3

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");
1
  • you want to do Match( content, "abc(..)" ); or something like that
    – tanascius
    Mar 10, 2010 at 14:30
1

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.

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.