hsobhy
hsobhy

Reputation: 1523

Compare and extract common words between 2 strings

In ASP.NET C# and assuming I have a string contains a comma separated words:

string strOne = "word,WordTwo,another word, a third long word, and so on";

How to split then compare with another paragraph that might and might not contain these words:

string strTwo = " when search a word or try another word you may find that  WordTwo is there with others";

Then how to output these common words departed with commas in a third string

string strThree = "output1, output2, output3";

To get a result like : "word, WordTwo, another word,"

Upvotes: 0

Views: 2544

Answers (2)

Drew Sumido
Drew Sumido

Reputation: 162

You will need to split strOne by comma, and use a contains against strTwo.

Note: You can't split strTwo by space and use intersect because your items may have spaces. i.e. "another word"

string strOne = "word,WordTwo,another word, a third long word, and so on";
string strTwo = " when search a word or try another word you may find that  WordTwo is there with others";
var tokensOne = strOne.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

var list = tokensOne.Where(x => strTwo.Contains(x));

var result = string.Join(", ",list);

Upvotes: 4

Jimmy JimJim
Jimmy JimJim

Reputation: 21

You could do something like this:

        string strOne = "word,WordTwo,another word, a third long word, and so on";
        string strTwo = " when search a word or try another word you may find that  WordTwo is there with others";
        string finalString = string.Empty;

        foreach (var line in strOne.Split(","))
        {
            if(strTwo.Contains(line))
                finalString += (line + ",");
        }

        finalString = finalString.Substring(0, finalString.Length - 1);
        Console.WriteLine(finalString);

Upvotes: 2

Related Questions