Reputation: 43
I am wondering how I can trim every string of an array after a certain char, for example I have 1 textbox in which I put a multiline string like:
HelloWorld:123
IAmABerliner:JFK
and then I want to click a Button and in the second TextBox everything in every line should be trimmed after the ":"
Output in Textbox 2:
HelloWorld
IamABerliner
Upvotes: 4
Views: 596
Reputation: 410
This might not be the most elegant solution, but this is what I came up with.
string input = TextBox1.Text;
string[] input_split = input.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
string output = "";
for(int i = 0; i < input_split.Length; i++)
{
string[] split_again = input_split[i].Split(':');
output += split_again[0];
}
TextBox2.Text = output;
I tested it and it gave the desired output.
Upvotes: 0
Reputation: 460
Following simple Code using StringBuilder and split working for me.
StringBuilder sb = new StringBuilder();
var st = textBox1.Text.Split('\n');
for (int i = 0; i < st.Length; i++)
{
sb.AppendLine(st[i].Split(':')[0]);
}
textBox2.Text = sb.ToString();
Upvotes: 0
Reputation: 30265
You can use this little snippet to get the string you want:
string trimmedInput = string.Join(
"\n",
input
.Split('\n')
.Select(s => s.Substring(0, s.IndexOf(":"))));
It firsts gets an array of all lines, then trims it after the semicolon and then puts them back together in one string rather an array of lines.
Upvotes: 0
Reputation: 3039
Just an alternative, and I'd really prefer the other methods, but you could also use regex:
txtInput.Text = System.Text.RegularExpressions.Regex.Replace(txtInput.Text, "(?m):.*$", string.Empty);
(?m)
turns on multiline mode:
matches literal colon.*
matches zero or more (*
) of any character except newline (.
)$
matches the end of the line (but not the newline) due to multiline mode being enabledUpvotes: 1
Reputation: 5341
Use the string.Split
method, and take just the first part of it:
string result = textBox2.Text.Split(':')[0];
For multiline strings:
string result = string.Empty;
foreach (string line in textBox2.Text.Split(Environment.NewLine.ToCharArray()))
{
result += line.Split(':')[0] + Environment.NewLine;
}
Upvotes: -2
Reputation: 10818
WinForms Texboxes have a Lines property.
You can iterate over those lines using Linq and split on :
, then take the First()
index
someTextBox.Lines = someTextBox.Lines.Select(x => x.Split(':').First()).ToArray();
Upvotes: 4