Let's say I had a string like this:
string source = "Today is friday! I'm am having trouble programming this. Today is friday! Tomorrow is saturday. Today is friday!"
I want to search through this string, grab all the sentences that say "Today is friday!", and create a new string with the sentences I just found.
The expected result from the above string is:
string output = "Today is friday!Today is friday!Today is friday!"
EDIT: LINQ is not mandatory.
Thanks!
Here's a non-LINQ method of doing it:
string str = "Today is friday! I'm am having trouble programming this. Today is friday! Tomorrow is saturday. Today is friday!";
StringBuilder sb = new StringBuilder();
int index = 0;
do
{
index = str.IndexOf("Today is friday!", index);
if (index != -1)
{
sb.Append("Today is friday!");
index++;
}
} while (index != -1);
string repeats = sb.ToString();
There is actually no need to find the matches. Since you are creating a new string based on your search pattern it will suffice if you simply have a count of the occurrences of the search string. You can replace the Regex with a faster substring counting algorithm if you like.
string source = "Today is friday! I'm am having trouble programming this. Today is friday! Tomorrow is saturday. Today is friday!";
string searchPattern = "Today is friday!";
int count = Regex.Matches(source, searchPattern).Count;
string result = string.Concat(Enumerable.Repeat(searchPattern, count));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With