2010-06-08 450 views

回答

3

一种选择是在换行符上拆分文本,更改结果数组的第二个元素,然后重新加入字符串并设置Text属性。类似于

string[] array = textBox.Text.Split('\n'); 
array[position] = newText; 
textBox.Text = string.Join('\n', array); 
0

您可以使用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; 
    } 
相关问题