1

I have a RichTextbox and I get the text within it as a string using this:

 richTextBox2.Lines = richTextBox2.Lines
                                   .Where(line => !line.Contains("any"))
                                   .ToArray();

I split the lines and remove the ones containing the string "any".

I want to select certain lines containing another string, then insert a custom string after that. How can I do that?

4
  • 1
    Can you provide an example input and output for what you are trying to achieve? Commented Jul 25, 2014 at 17:28
  • 1
    You want to add a new line or just add the custom string after the first string on the same line? Commented Jul 25, 2014 at 17:29
  • john, I want to add the custom string after the first string on the same line. thanks for editing my question Commented Jul 25, 2014 at 17:33
  • Just add a 'Select` and use a line.Replace for your old text to "old text + new text" Commented Jul 25, 2014 at 17:35

1 Answer 1

4

This adds the custom string right after the found one:

richTextBox2.Lines = richTextBox2.Lines
                         .Where(line => !line.Contains("any"))
                         .Select(line => line.Replace("findme", "findme and addme"))
                         .ToArray();

This adds the custom string at the end of the line:

richTextBox2.Lines = richTextBox2.Lines
                         .Where(line => !line.Contains("any"))
                         .Select(line => 
                             line + (line.Contains("findme") ? " and addme" : "")
                         )
                         .ToArray();
Sign up to request clarification or add additional context in comments.

6 Comments

is there a way to keep the text the line had before, but just adding 2 or 3 characters at the end of the whole line? thanks for correcting my question.
@verax That's exactly what my second example does. Inside of the Select, it says "return the line PLUS (if the line has this text, return additional text, otherwise don't add anything)."
yes, I didn't refresh the site did not see it, Thank you so much
I'm sorry Moshe, what if I want to select a line that starts with "any"?
Use line.StartsWith instead of line.Contains .
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.