[英]Replace a character in specific position if line starts with condition C#
I am trying to modify a txt file, I need to change the 45 character with a P if the line starts with 8我正在尝试修改 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);
}}
To accomplish your goal the code could be changed in this way为了实现您的目标,可以通过这种方式更改代码
//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";
}
}
The key points changed are the way to select into a textbox.更改的关键点是将 select 放入文本框的方式。 The Select method requires a starting index and the number of character to select , finally, once you have a SelectedText, (a read/write property) you can simply replace the current SelectedText with your own text. Select 方法需要一个起始索引和select 的字符数,最后,一旦你有一个 SelectedText,(读/写属性)你可以简单地用你自己的文本替换当前的 SelectedText。 Lot easier than your current (and wrong) calculation.比您当前的(和错误的)计算容易得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.