如果行以条件 C# 开头,则替换特定位置的字符

Replace a character in specific position if line starts with condition C#

我正在尝试修改一个 txt 文件,如果该行以 8 开头,我需要将第 45 个字符更改为 P

for (int i = 0; i < textBox.Lines.Length; i++)//Loops through each line of text in RichTextBox
           {

               string text = textBox.Lines[i];
               if ((text.Contains("8") == true)) //Checks if the line contains 8.
               {
                   char replace = 'P';
                   int startindex = textBox.GetFirstCharIndexFromLine(i);
                   int endindex = text.Length;
                   textBox.Select(startindex, endindex);//Selects the text.
                   richTextBox1.Text = textBox.Text.Substring(0, textBox.SelectionStart) + (0, textBox.Lines) + replace + textBox.Text.Substring(textBox.SelectionStart + 45);
     }}             

为了实现您的目标,可以这样更改代码

//Loops through each line of text in RichTextBox
for (int i = 0; i < textBox.Lines.Length; i++)
{
    string text = textBox.Lines[i];
    //Checks if the line starts with "8".
    if (text.StartsWith("8")) 
    {
        // Find the 45th position from the start of the line
        int startindex = textBox.GetFirstCharIndexFromLine(i) + 45;
        // Starting from the found index select 1 char
        textBox.Select(startindex, 1);
        // Replace the selected char with the "P"
        textBox.SelectedText = "P";
    }
}

更改的关键点是select进入文本框的方式。 Select 方法需要一个起始索引和 个字符到 select,最后,一旦你有了一个 SelectedText,(一个 read/write 属性) 您可以简单地用您自己的文本替换当前的 SelectedText。比您当前的(和错误的)计算要容易得多。