How to find a string template and print it from my text file using C #

I have a text file with the string "abcdef"

I want to find the string "abc" in my test file ... and print the next two characters for abc .. where is it "de".

How could I do this? what class and function?

+4
source share
4 answers

Try the following:

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 an error. I fixed it.

+3
source

Read the file line by line using something like:

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

Or you can use regular expressions.

 Match match = Regex.Match(line, "REGEXPRESSION_HERE"); 
+3
source

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 that there will always be two characters after the string instance.

+1
source

I think this is a clearer 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 match. I do not know if you want to show all matches.

0
source

Source: https://habr.com/ru/post/1303675/


All Articles