首页 > 解决方案 > 如果行以条件 C# 开头,则替换特定位置的字符

问题描述

我正在尝试修改 txt 文件,如果行以 8 开头,我需要用 P 更改 45 字符

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);
     }}             

标签: c#replacepositionsubstring

解决方案


为了实现您的目标,可以通过这种方式更改代码

//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 方法需要一个起始索引和要选择的字符数,最后,一旦你有一个 SelectedText,(一个读/写属性),你可以简单地用你自己的文本替换当前的 SelectedText。比您当前的(和错误的)计算容易得多。


推荐阅读