问题描述
我想编写一个应用程序,对我从源代码复制并粘贴到RichTextBox区域中的文本行进行随机排序.
I want to write an application which sorts randomly line of text which I copy from a source and paste into RichTextBox area.
但是,有一个条件-文本被格式化(某些单词为粗体,下划线等).有什么建议吗?看起来如何?
However, there is one condition - text is formatted (some words are in bold, underline etc.). So any suggestions? How should it look like?
我认为我应该使用RichTextBox.Rtf
之类的东西,但我确实是一个初学者,我感谢每个提示或示例代码.
I think I should use RichTextBox.Rtf
or something but I am really a beginner and I appreciate every hint or example code.
谢谢
推荐答案
有点棘手.您可以像这样检索格式化的RTF文本行
It is a bit tricky. You can retrieve the formatted RTF text lines like this
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
Clear the RichtTextBox
richTextBox1.Text = "";
最好以相反的顺序插入行,因为这样可以更容易地选择文本的开头
Inserting the lines is best done in reverse order because it is easier to select the beginning of the 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";
}
这篇关于RichTextBox-随机对行进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!