Parsing a string and searching for specific text in C #

I have a line that contains, lets say the word "key" 5 times. Every time I see the word "key" on this line, I want to print some text. How can I parse this line, find all the "keywords" and print the texts accordingly? 5 words "key" - 5 printed texts. This needs to be done in C #.

Thanks in advance.

+4
source share
4 answers

How about using Regex.Matches :

 string input = ... string toPrint = ... foreach (Match m in Regex.Matches(input, "key")) Console.WriteLine(toPrint); 

EDIT . If the word "word" means "whole words", you need another regular expression, for example:

 @"\bkey\b" 
+7
source

Inside the loop, you can use the substring () method, which offers an initial position parameter, and with each iteration you advance the initial position; the loop exits when you reach a condition not found in the line. EDIT: for printing text, which will depend on where you want to print it. EDIT2: You also need to consider whether the target line can be displayed in a way that you do not consider a true β€œhit”:

  The key to success, the master key, is getting off your keyster... 
0
source

I have an extension method that I use for strings to get substring indices, since .Net provides only IndexOf (the only result for the first substring match).

 public static class Extensions { public static int[] IndexesOf(this string str, string sub) { int[] result = new int[0]; for(int i=0; i < str.Length; ++i) { if(i + sub.Length > str.Length) break; if(str.Substring(i,sub.Length).Equals(sub)) { Array.Resize(ref result, result.Length + 1); result[result.Length - 1] = i; } } return result; } } 

You can use the extension method for all instances of the print key.

 int[] indexes = stringWithKeys.IndexesOf("key"); foreach(int index in indexes) { // print something } 

I know that my sample code may be the longest, but the extension method can be reused, and you can put it in a utility-type library for future reference.

0
source

If it is a verbose string, you can use LINQ.

 string texttosearch; string texttofind; string[] source = texttosearch.Split(new char[] { '.', '?', '!', ' ', ';', ':', ',' }, StringSplitOptions.RemoveEmptyEntries); var matchQuery = from word in source where word.ToLowerInvariant() == texttofind.ToLowerInvariant() select word; foreach (string s in matchquery) console.writeline(whatever you want to print); 
0
source

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


All Articles