Reputation: 214
I have a textbox with multiline enabled, and want to add a string at the beginning and end of each line, so every line would be changed to
a + line + b
Now I know it has to do with a foreach loop, but don't know how to write it out.
Upvotes: 1
Views: 4880
Reputation: 687
Here is what i use to add the characters a and b to the beginning and the end to a string that contains a bunch of lines :
public string Script;
string[] lines = Script.Split(new[] { '\r', '\n' });
for (int i = 0; i < lines.Length; i++)
{
lines[i] = a + lines[i] + b;
if (!lines[i].Equals("\"\"+"))
{
Console.WriteLine(lines[i]);
Result += lines[i]+"\n";
}
}
Upvotes: 0
Reputation: 700422
You can use a replace on the entire text:
text = a + text.Replace(Environment.NewLine, b + Environment.NewLine + a) + b;
Upvotes: 2
Reputation: 16747
Since you mentioned foreach, here's another way.
var newLines = new List<string>(textBox1.Lines.Length);
foreach (string line in textBox1.Lines)
newLines.Add(a + line + b);
textBox1.Lines = newLines.ToArray();
Upvotes: 0
Reputation: 1501043
Well, the Lines
property is probably the one you want. Three options:
string[] lines = textBox.Lines;
for (int i = 0; i < lines.Length; i++)
{
lines[i] = a + lines[i] + b;
}
textBox.Lines = lines;
Or:
textBox.Lines = Array.ConvertAll(textBox.Lines, line => a + line + b);
Or:
textBox.Lines = textBox.Lines
.Select(line => a + line + b)
.ToArray();
Upvotes: 6