C# 多行文本框:如果包含 X,则在行后添加一个字符串
C# Multiline Textbox: Adding a string after a line if it contains X
我想做的是循环多行文本框的内容(逐行循环),如果它包含某个关键字(例如,如果该行包含单词:click()
)然后在下一行我会添加单词 sleep(5)
循环文本框没有问题:
foreach (string line in txtBoxAdd.Lines)
{
if (line.Contains("click()"))
{
Helpers.ReturnMessage(line);
}
}
我有问题的部分是如何在找到关键字 click()
后在下一行添加单词 sleep(5)
。
如有任何帮助,我们将不胜感激。
你可以这样做:
List<string> lines = new List<string>(textBox1.Lines);
for(int i = 0; i < lines.Count; i++)
{
if (lines[i].Contains("click()"))
{
lines.Insert(i + 1, "sleep(5)");
i++;
}
}
textBox1.Lines = lines.ToArray();
请注意,它不会检查下一行是否已经存在 "sleep(5)",并且在整个内容处理完成之前,更改不会应用于文本框。
流畅版:
using System;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
txtBoxAdd.Lines = new[] { "Line 1", "Line 2", "Line 3 contains the buzzword", "Line 4", "Line 5 has the buzzword too", "Line 6" };
}
private void button1_Click(object sender, EventArgs e)
{
InsertLineAfterBuzzword(buzzword: "buzzword", lineToAdd: "line to add");
}
private void InsertLineAfterBuzzword(string buzzword, string lineToAdd)
{
txtBoxAdd.Lines = txtBoxAdd.Lines
.SelectMany(i => i.Contains(buzzword) ? new[] { i, lineToAdd } : new[] { i })
.ToArray();
}
}
}
我想做的是循环多行文本框的内容(逐行循环),如果它包含某个关键字(例如,如果该行包含单词:click()
)然后在下一行我会添加单词 sleep(5)
循环文本框没有问题:
foreach (string line in txtBoxAdd.Lines)
{
if (line.Contains("click()"))
{
Helpers.ReturnMessage(line);
}
}
我有问题的部分是如何在找到关键字 click()
后在下一行添加单词 sleep(5)
。
如有任何帮助,我们将不胜感激。
你可以这样做:
List<string> lines = new List<string>(textBox1.Lines);
for(int i = 0; i < lines.Count; i++)
{
if (lines[i].Contains("click()"))
{
lines.Insert(i + 1, "sleep(5)");
i++;
}
}
textBox1.Lines = lines.ToArray();
请注意,它不会检查下一行是否已经存在 "sleep(5)",并且在整个内容处理完成之前,更改不会应用于文本框。
流畅版:
using System;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
txtBoxAdd.Lines = new[] { "Line 1", "Line 2", "Line 3 contains the buzzword", "Line 4", "Line 5 has the buzzword too", "Line 6" };
}
private void button1_Click(object sender, EventArgs e)
{
InsertLineAfterBuzzword(buzzword: "buzzword", lineToAdd: "line to add");
}
private void InsertLineAfterBuzzword(string buzzword, string lineToAdd)
{
txtBoxAdd.Lines = txtBoxAdd.Lines
.SelectMany(i => i.Contains(buzzword) ? new[] { i, lineToAdd } : new[] { i })
.ToArray();
}
}
}