Click here to Skip to main content
15,885,767 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone.
I wanted to remove everything after a specific character in each row in textBox1.Text multiline.
This below is the code for remove everything after specific character, but for textBox single line:
How to do it for textBox multiline?

For example,
before executing the code:

www.page.1.com/page.2/page.3
www.home.page.net/about.page
www.samepage.org/
www.text1.com/text2

I want it to look like this after executing the code:

www.page.1.com
www.home.page.net
www.samepage.org
www.text1.com

Thank you.


What I have tried:

C#
string str = textBox1.Text;
            if (str.Contains('/'))
            {
                int index = str.IndexOf('/');
                string result = str.Substring(0, index);
                textBox1.Text = result;
            }
Posted
Updated 11-Feb-20 4:01am

What you could do is loop over the Lines property and do something like this:
C#
for (int i=0; i < textBox1.Lines.Length; i++)
{
  string line = textBox1.Lines[i];
  if (line.Contains('/'))
  {
     int index = line.IndexOf('/');
     textBox1.Lines[i] = line.Substring(0, index);
  }
}
 
Share this answer
 
Comments
Maciej Los 11-Feb-20 14:49pm    
5ed!
Pete O'Hanlon 11-Feb-20 15:43pm    
Thanks.
TheRealSteveJudge 12-Feb-20 2:34am    
Short but effective solution for Windows Forms. 5*
Pete O'Hanlon 12-Feb-20 3:00am    
Thanks.
First of all you must split the TextBox text into separate lines.
When you watch the TextBox text property with the debugger,
you will see that it actually is like this:

http://www.page.1.com/page.2/page.3\r\nwww.home.page.net/about.page"...

The linebreaks are \r\n

You get the lines like this
C#
var lines = Regex.Split(textBox.Text, "\r\n");

Now you must loop through the lines and get the first part of any URL by using String.Split:
C#
var newLines = new List<string>();

foreach (var line in lines)
{
    var firstChunk = line.Split('/')[0];

    newLines.Add(firstChunk);
}

Finally you must join the lines with the linebreaks.
C#
textBox.Text = string.Join("\r\n", newLines);
 
Share this answer
 
Comments
Member 10410972 11-Feb-20 10:36am    
Thank you, this works.
The problem is solved.
Maciej Los 11-Feb-20 14:50pm    
5ed!
TheRealSteveJudge 12-Feb-20 2:11am    
Thank you, Maciej!
Pete O'Hanlon 12-Feb-20 3:00am    
I like it. 5.
TheRealSteveJudge 12-Feb-20 3:49am    
Thank you, Peter!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900