willerson
willerson

Reputation: 79

C# Multiline Textbox: Adding a string after a line if it contains X

What I'm trying to do is loop the contents of a multiline textbox (looping line by line), if it contains a certain keyword (for example if the line contains the word: click()) then on the next line i would add the word sleep(5)

Looping the textbox is no problem:

foreach (string line in txtBoxAdd.Lines)
{
   if (line.Contains("click()"))
   {
      Helpers.ReturnMessage(line);
   }
}

The part i am having an issue with is how to add the word sleep(5) on the next line after it has found the keyword click() for example.

Any help would be appreciated.

Upvotes: 0

Views: 333

Answers (2)

Idle_Mind
Idle_Mind

Reputation: 39132

You could do something like this:

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

Note that it doesn't check to see if there is already a "sleep(5)" on the next line, and that the changes aren't applied to the textbox until the whole thing has been processed.

Upvotes: 3

CSDev
CSDev

Reputation: 3235

Fluent version:

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

Upvotes: 1

Related Questions