Find a string in a text few times and do action each time

94 Views Asked by At

I want to find all strings in a text with WatiN. I can find the first string, but i can't gather all of them. For example I want find all occurrences of "water" in this text:

There is a lot of water on earth. But not all water is drinkable.

So here I should find 2 "water". My code only finds the first one. How can I find both of them?

My code is:

IE ie = new IE("http://examplesite.com");

Element test = ie.Table(Find.ByClass("dataTable")).Element("td");

ie.TableRow(Find.ByText(t => t.Contains("example string"))).TextField(Find.ByName("examplename")).Button(Find.ByValue("example value")).Click();

ie.WaitForComplete();
Console.WriteLine("finished");
2

There are 2 best solutions below

0
Berend On

You can use IndexOf in a loop to find multiple occurrences of a substring.

const string haystack = "there are lots of water in the earth. but all of water arent drinkble.";
const string needle = "water";

var startIndex = -1;
while ((startIndex = haystack.IndexOf(needle, startIndex + 1)) > -1)
{
    Console.WriteLine("Found {0} at {1}", needle, startIndex);
}
3
Craig W. On

Split the string then grab all the entries that contain what you're looking for.

var sentence = "There is a lot of water on earth. But not all water is drinkable."
var parts = sentence.Split(' ');
var words = parts.Where(p => p == "water");