如何在RichTextBox中使用指定字符拼接选中行并替换原有行
RichTextBox选中多行拼接实现方案
实现逻辑
- 定位选中内容对应的起始行、结束行索引,提取选中范围内的所有行文本
- 用指定分隔符拼接所有提取到的行文本
- 替换原有选中的多行内容为拼接后的新行
代码实现(C# WinForm)
// 入参:目标RichTextBox控件,自定义拼接分隔符 public void ConcatSelectedLines(RichTextBox richTextBox, string separator) { richTextBox.SuspendLayout(); // 获取选中区域对应的起止行索引 int startLine = richTextBox.GetLineFromCharIndex(richTextBox.SelectionStart); int endLine = richTextBox.GetLineFromCharIndex(richTextBox.SelectionStart + richTextBox.SelectionLength); // 收集选中行内容,TrimEnd处理行尾换行符 List<string> selectedLines = new List<string>(); for (int i = startLine; i <= endLine; i++) { selectedLines.Add(richTextBox.Lines[i].TrimEnd('\r', '\n')); } // 拼接得到新行 string mergedLine = string.Join(separator, selectedLines); // 计算要替换的字符范围 int replaceStartIndex = richTextBox.GetFirstCharIndexFromLine(startLine); int replaceLength; if (endLine < richTextBox.Lines.Length - 1) { replaceLength = richTextBox.GetFirstCharIndexFromLine(endLine + 1) - replaceStartIndex; } else { replaceLength = richTextBox.TextLength - replaceStartIndex; } // 执行替换 richTextBox.Select(replaceStartIndex, replaceLength); richTextBox.SelectedText = mergedLine; richTextBox.ResumeLayout(); }
调用示例
如果你要使用-作为分隔符,直接调用方法即可:ConcatSelectedLines(yourRichTextBoxControl, " - ");
效果验证
原文本:
The situation is dire But momma raised up a fighter It's all come down to the wire But the come-up is higher
选中前两行调用方法后,得到效果:
The situation is dire - But momma raised up a fighter It's all come down to the wire But the come-up is higher
选中后两行调用方法后,得到效果:
The situation is dire But momma raised up a fighter It's all come down to the wire - But the come-up is higher
内容的提问来源于stack exchange,提问作者vahid Araghi
相关产品推荐
相关产品推荐

