【问题标题】:RichTextBox - sorting lines randomlyRichTextBox - 随机排序行
【发布时间】:2012-04-02 10:02:30
【问题描述】:

我想编写一个应用程序,它对我从源复制并粘贴到 RichTextBox 区域的随机文本行进行排序。

但是,有一个条件 - 文本被格式化(有些词是粗体、下划线等)。那么有什么建议吗?它应该是什么样子?

我认为我应该使用RichTextBox.Rtf 或其他东西,但我真的是一个初学者,我很欣赏每一个提示或示例代码。

谢谢

【问题讨论】:

标签: c# sorting random richtextbox


【解决方案1】:

这有点棘手。您可以像这样检索格式化的 RTF 文本行

string[] rtfLines = new string[richTextBox1.Lines.Length];
for (int i = 0; i < rtfLines.Length; i++) {
    int start = richTextBox1.GetFirstCharIndexFromLine(i);
    int length = richTextBox1.Lines[i].Length;
    richTextBox1.Select(start, length);
    rtfLines[i] = richTextBox1.SelectedRtf;
}

现在你可以像这样洗牌

var random = new Random();
rtfLines = rtfLines.OrderBy(s => random.NextDouble()).ToArray();

清除 RichtTextBox

richTextBox1.Text = "";

最好以相反的顺序插入行,因为这样更容易选择文本的开头

// Insert the line which will be the last line.
richTextBox1.Select(0, 0);
richTextBox1.SelectedRtf = rtfLines[0];

// Prepend the other lines and add a line break.
for (int i = 1; i < rtfLines.Length; i++) {
    richTextBox1.Select(0, 0);

    // Replace the ending "}\r\n" with "\\par }\r\n". "\\par" is a line break.
    richTextBox1.SelectedRtf =
        rtfLines[i].Substring(0, rtfLines[i].Length - 3) + "\\par }\r\n";
}

【讨论】:

  • 谢谢,这似乎工作得很好:) 但这里还有一件事。我向richboxtext 添加了上下文菜单,只有一个“粘贴”功能。什么代码会将我的剪贴板内容粘贴到richboxtext 表单中?我试过: private void PasteToolStripMenuItem_Click_1(object sender, EventArgs e) { richTextBox1.Text = Clipboard.GetText(); } 但它会粘贴非格式化文本。如何粘贴带有格式的文本?
  • richTextbox1.Paste(); 或者您可以使用组合键Ctrl-C
【解决方案2】:

任务似乎并不复杂(如果我理解正确的话)。 将剪贴板转换为字符串,然后解析为数组 - 使用 Split()。 然后确定您需要多少随机事件并遍历每个单词;为每次迭代生成随机数(应该与事件的数量相匹配),将该数字与其中一个事件相交并将该大小写应用于该特定单词。也许不是最有效的方法,但这就是我想到的

【讨论】:

  • 您不能使用String.Split,因为RTF-Lines 不只是用\r\n 分隔。由于 OP 想要保持 RTF 格式,所以事情有点复杂。
猜你喜欢
  • 2013-02-27
  • 1970-01-01
  • 2012-12-04
  • 2011-05-21
  • 2012-11-19
  • 2012-03-16
  • 2012-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多