简体   繁体   中英

How to 'Trim' a multi line string?

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?

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

This trims each line

temp2 = string.Join(Environment.NewLine, 
    temp2.Split(new []{Environment.NewLine},StringSplitOptions.None)
         .Select(l => l.Trim()));
string temp3 = String.Join(
                    Environment.NewLine, 
                    temp2.Split(new char[] { '\n', '\r' },StringSplitOptions.RemoveEmptyEntries)
                         .Select(s => s.Trim()));

split, trim, join

string[] lines = temp1.Split(new []{Environment.NewLine});
lines = lines.Select(l=>l.Trim()).ToArray();
string temp2 = string.Join(Environment.NewLine,lines);

You could use regular expressions to do this.

Here's a PHP (I'm on a Mac, so no C#) preg_replace example that does this

<?php

$test = "   line 1     
     line 2 with blanks at end     
     line 3 with tabs at end        ";

print $test;

$regex = '/[ \t]*\n[ \t]*/';
$res = trim(preg_replace($regex, "\n", $test));
print $res;

The regex preg_replace removes the blanks around line feeds, the trim removes those at the beginning and end.

The C# Regex.Replace method should work like the preg_replace.

Off topic, but in PowerShell watch-out when you use this code:

$content = Get-Content file.txt;
$trimmed = $content.Trim();

Since, not obviously, $content is an array of lines so PS will magically perform a Trim for each line.

Forcing it into a string:

[System.String]$content = Get-Content file.txt;

Won't work since PowerShell then removes all carriage returns to make a single line..!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM