复制到剪贴板时,StringBuilder 在末尾返回字符串列表 + 换行符?

StringBuilder returning list of strings + a NewLine at the end when copying to clipboard?

我有一个循环,每次循环时都会添加一个新行。当它完成时,我将 StringBuilder.ToString() 复制到剪贴板并将其粘贴到记事本中,闪烁的光标保留在它下面的新行上,而不是在最后一个字符串的末尾。我怎样才能防止这种情况发生并且光标停留在最后一个字符串的末尾,而不是在它下面换行?

StringBuilder sbItems = new StringBuilder();
for (int i = 0; i < 10; i++)
{
    sbItems.AppendLine("Item #" + i.ToString());

}
Clipboard.SetText(sbItems.ToString());

只是 Trim() 字符串

Returns a new string in which all leading and trailing occurrences of a set of specified characters from the current String object are removed.

Clipboard.SetText(sbItems.ToString().Trim());

我看到您复制到剪贴板的字符串以新行结尾。当然,这一新行已粘贴,因此您的光标位于新行上。

你必须以某种方式摆脱这条新线。执行此操作的方法取决于您的精确规格:

If the string is copied to the clipboard, the complete string is copied to the clipboard

如果这是您的规范,那么粘贴您复制的字符串的每个人都将以您的字符串末尾的新行结尾。如果贴纸是你无法控制的程序,你也无能为力

另一个规范可以是:

If the string is copied to the clipboard, all but a possible terminating new line is copied to the clipboard

这样你会得到你想要的,粘贴者不会看到终止的新行。但是要注意,这样剪贴板上的字符串不是原来的字符串。

代码(当然可以优化,只是展示小步骤)

StringBuilder sbItems = FillStringBuilder(...);
// before copying, remove a possible new line character
// for this we use property System.Environment.NewLine
var stringToCopyToClipboard = sbItems.ToString();
if (stringToCopyToClipboard.EndsWith(Environment.NewLine)
{
    int newLineIndex = stringToCopyToClipboard.LastIndexOf(Environment.NewLine);
    stringToCopyToClipboard = stringToCopyToClipboard.Substring(0, newLineIndex);
}
Clipboard.SetText(stringToCopyToClipboard);