C#搜索剪贴板中存储的单词并将搜索到的单词输出到剪贴板

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

我是 C# 的新手,需要帮助格式化我正在尝试从剪贴板中读取特定单词的代码,然后将其输出回剪贴板。在字符串列表搜索中需要我添加无穷无尽的数字或单词。

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

您的代码几乎没问题。

我认为您需要用空格或逗号分隔剪贴板中的单词,但您需要找到一些东西来执行此操作。

然后:

var Text = Clipboard.GetText();

//imagine you have words, chair, table
//you split to have an array containing 
var arrayString = Text.Split(',')

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

//you check your list
var result = wordswordsToSearch.Where(i => arrayString.Contains(i)).ToList();

//and set clipboard with matching content
var TextOut = Clipboard.SetText(result);

\outputs “chair, table” to the clipboard

我不知道我的代码是否有效,但这是我从您的需求中了解到的想法。

你遇到的问题是 result 是一个单词列表,但你不能将列表放在剪贴板上。你必须把它变成一个字符串。

您可以使用 Join 方法 (string.Join) 执行此操作,并指定要在单词之间放置的内容,即逗号和 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);