0

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,"

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
hsobhy
  • 1,493
  • 2
  • 21
  • 35

2 Answers2

4

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);
Drew Sumido
  • 162
  • 1
  • 5
2

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);