在.Net中的文本框的特定行中插入文本
问题描述:
我想在特定行中插入文本,并替换同一行中的文本。在.Net中的文本框的特定行中插入文本
如
This is line 1
This is line 2
This is line 3
现在我想在第2行文字替换到 这是新的生产线2
这可能吗?
答
一种选择是在换行符上拆分文本,更改结果数组的第二个元素,然后重新加入字符串并设置Text属性。类似于
string[] array = textBox.Text.Split('\n');
array[position] = newText;
textBox.Text = string.Join('\n', array);
答
您可以使用RegEx对象来分割文本。
调用ReplaceLine()方法是这样的:
private void btnReplaceLine_Click(object sender, RoutedEventArgs e)
{
string allLines = "This is line 1" + Environment.NewLine + "This is line 2" + Environment.NewLine + "This is line 3";
string newLines = ReplaceLine(allLines, 2, "This is new line 2");
}
的ReplaceLine()方法实现:
private string ReplaceLine(string allLines, int lineNumber, string newLine)
{
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(Environment.NewLine);
string newLines = "";
string[] lines = reg.Split(allLines);
int lineCnt = 0;
foreach (string oldLine in lines)
{
lineCnt++;
if (lineCnt == lineNumber)
{
newLines += newLine;
}
else
{
newLines += oldLine;
}
newLines += lineCnt == lines.Count() ? "" : Environment.NewLine;
}
return newLines;
}