简体   繁体   English

如何从剪贴板中正确提取字符串

[英]How do I properly extract a string from the clipboard

So i'm trying to get the links from the clipboard, I manage to work it out just fine if I have one but I changed my method a bit because let's say I have more than 1 link saved in my clipboard. 因此,我尝试从剪贴板中获取链接,如果有链接,我会设法解决,但是我稍微改变了方法,因为我在剪贴板中保存了多个链接。 I get this error 我得到这个错误

Cannot convert type 'char' to 'string' 无法将类型'char'转换为'string'

I dont see why, everything returns a string or a bool. 我不明白为什么,一切都返回字符串或布尔值。 What is causing this error and how do I resolve it? 是什么导致此错误,我该如何解决?

if (Clipboard.ContainsText(TextDataFormat.Text))
{
    string clipboardText = Clipboard.GetText(TextDataFormat.Text);
    foreach (string link in clipboardText)
    {
        if (Uri.TryCreate(link, UriKind.Absolute, out var uri))
        {
            rtbLinks.AppendText(uri + "\n");
        }
    }
}

A foreach-loop loops through a collection or an array. foreach循环遍历集合或数组。 In your case, you are using the string as the collection/array. 在您的情况下,您正在使用字符串作为集合/数组。 That is somewhat possible; 那是有可能的。 imagine a string as an array of type char. 想象一个字符串为char类型的数组。

You could use 你可以用

foreach (char link in clipboardText)
{
    if (Uri.TryCreate(link, UriKind.Absolute, out var uri))
    {
        rtbLinks.AppendText(uri + "\n");
    }
}

That would only loop through each character of the string, though, and would not really solve your problem. 但是,那只会遍历字符串的每个字符,并不能真正解决您的问题。

Have a look at this for more information on the foreach-loop. 看看这个以获得更多关于foreach循环的信息。

What you really need is an array of type string, where you store the links. 您真正需要的是一个字符串类型的数组,用于存储链接。 I imagine you have those strings split by a delimiter (like "|") in your clipboard, so you could modify your code like this: 我想您的剪贴板中有用定界符(例如“ |”)分隔的字符串,因此您可以像这样修改代码:

if (Clipboard.ContainsText(TextDataFormat.Text)) {
    string[] clipboardText = Clipboard.GetText(TextDataFormat.Text).Split('|');
    foreach (string link in clipboardText) {
        if (Uri.TryCreate(link, UriKind.Absolute, out var uri)) {
            rtbLinks.AppendText(uri + "\n");
        }
    }
}

If you have, eg "https://softwareengineering.stackexchange.com|https://stackoverflow.com" in your clipboard, it will split the links into the array of string and you can work with those. 如果您的剪贴板中有"https://softwareengineering.stackexchange.com|https://stackoverflow.com" ,它将把链接分成字符串数组,您可以使用它们。

Without a delimiter, things might get a bit more tricky. 没有定界符,事情可能会变得有些棘手。 You would then have to manually split those links into the string array first, and loop through that array afterwards. 然后,您必须先手动将这些链接拆分为字符串数组,然后再遍历该数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM