Search code examples
c#stringwinformsedittrim

C# Automation Multiline String Trim


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


Solution

  • 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;
    }