SmartestVEGA
SmartestVEGA

Reputation: 8909

how to find a string pattern and print it from my text file using C#

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?

Upvotes: 4

Views: 2546

Answers (4)

Steven
Steven

Reputation: 172855

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.

Upvotes: 3

Javier
Javier

Reputation: 4141

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.

Upvotes: 0

Elisha
Elisha

Reputation: 23800

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.

Upvotes: 1

thelost
thelost

Reputation: 6694

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");

Upvotes: 3

Related Questions