c# - 如果行以条件 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);
}}
解决方案
为了实现您的目标,可以通过这种方式更改代码
//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。比您当前的(和错误的)计算容易得多。
推荐阅读
- c++ - 如何优化以下代码?(它在arduino中)
- php - 使用 PHP 为使用 PHP 的多个 URL 交换 Divs 的显示
- jenkins - 在詹金斯管道中运行柏树测试得到错误
- html - 不悬停时反向过渡
- aws-step-functions - 需要了解阶跃函数重试机制
- javascript - 如何在我的 toast 通知上添加撤消按钮?
- python - python - 如何确保字符串中的最后2个字符至少有一个数字与python regex
- python - UnboundLocalError:分配前引用的局部变量“图像”
- postgresql - 如何在 LAG 函数列上使用运算符
- javascript - How write the labels of the data inside a Doughnut Chart made with Chart.js?