0
我想在特定行中插入文本,並替換同一行中的文本。在.Net中的文本框的特定行中插入文本
如
This is line 1
This is line 2
This is line 3
現在我想在第2行文字替換到 這是新的生產線2
這可能嗎?
我想在特定行中插入文本,並替換同一行中的文本。在.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;
}