Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to 'Trim' a multi line string?

Tags:

string

c#

text

trim

I am trying to use Trim() on a multi line string, however only the first line will Trim(). I can't seem to figure out how to remove all white space from the beginning of each line.

string temp1 = "   test   ";
string temp2 = @"   test
                    line 2 ";

MessageBox.Show(temp1.Trim());
//shows "test".

MessageBox.Show(temp2.Trim());
//shows "test"
        "       line2 ".

Can I use Trim/TrimStart/TrimEnd on a multi line string?

like image 800
Fuzz Evans Avatar asked Jan 07 '13 23:01

Fuzz Evans


People also ask

How do you break a string with two lines?

You can use the . split() method and the . join() method together to split a string into multiple lines.

How do I display text on multiple lines?

Click the Display tab. To enable multiple lines of text to be typed in the text box, select the Multi-line check box, and then optionally do one of the following: To prevent users from being able to insert paragraph breaks in the text box by pressing ENTER, clear the Paragraph breaks check box.

What does C# TRIM () do?

The Trim() method in C# is used to return a new string in which all leading and trailing occurrences of a set of specified characters from the current string are removed.


2 Answers

Can I use Trim/TrimStart/TrimEnd on a multi line string?

Yes, but it only Trims the string as a whole, and does not pay attention to each line within the string's content.

If you need to Trim each line, you could do something like:

string trimmedByLine = string.Join(
                             "\n", 
                             temp2.Split('\n').Select(s => s.Trim()));
like image 172
Reed Copsey Avatar answered Sep 19 '22 17:09

Reed Copsey


This trims each line

temp2 = string.Join(Environment.NewLine, 
    temp2.Split(new []{Environment.NewLine},StringSplitOptions.None)
         .Select(l => l.Trim()));
like image 43
Tim Schmelter Avatar answered Sep 17 '22 17:09

Tim Schmelter