Search code examples
c#textboxmultiline

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.


Solution

  • 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.