Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find all occurrences of a specific sentence within a string?

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!

like image 620
Jeff Avatar asked Dec 04 '22 02:12

Jeff


2 Answers

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();
like image 79
itsme86 Avatar answered Apr 28 '23 14:04

itsme86


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));
like image 28
Martin Devillers Avatar answered Apr 28 '23 14:04

Martin Devillers