Search code examples
c#listclipboardcontains

C# search for words stored in clipboard and output searched words to the clipboard


I am new to C# and need help formatting this code I am trying read from the clipboard for specific words then output it back to the clipboard. There will need to be an endless number or words for me to add in the string list search.

Text = Clipboard.GetText();

string Text = "Text to analyze for words, chair, table";

List<string> words = new List<string> { "chair", "table", "desk" };

var result = words.Where(i => Text.Contains(i)).ToList();

TextOut = Clipboard.SetText();

\\outputs “chair, table” to the clipboard

Solution

  • The problem you have is that result is a list of words, but you can't put a list on the clipboard. You have to turn it into a string.

    You can do this using the Join method (string.Join), and specifying what you want to put in between the words, which is a comma and a space:

            //string Text = Clipboard.GetText();
            string Text = "Text to analyze for words, chair, table";
    
            List<string> words = new List<string> { "chair", "table", "desk" };
    
            // No need for ToList - the enumerable will work with Join
            IEnumerable<string> foundWords = words.Where(i => Text.Contains(i)); 
            string result = string.Join(", ", foundWords);
            Clipboard.SetText(result);