Monday, September 5, 2022

[FIXED] How to 'Trim' a multi line string?

Issue

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?


Solution

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()));


Answered By - Reed Copsey
Answer Checked By - Timothy Miller (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.