我是新的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),并指定要在单词之间插入的内容,即逗号和空格:
//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);