Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim the contents of a String array in C#

    String []lines = System.IO.File.ReadAllLines(path);
    foreach (String line in lines)
    {
        line.Trim();
    }

Obviously this doesn't work because String.Trim returns the Trimmed version as a new String. And you can't do line = line.Trim(). So is the only way to do this an old-school for loop?

    for(int i=0;i<lines.Length;++i)
    {
        lines[i] = lines[i].Trim();
    }

Note I am restricted to Visual Studio 2005 i.e. .Net 2.0

like image 877
Mr. Boy Avatar asked Dec 21 '12 13:12

Mr. Boy


1 Answers

lines.Select(l => l.Trim()).ToArray();

Alternatively, for .NET 2.0:

static IEnumerable<string> GetTrimmed(IEnumerable<string> array)
{
    foreach (var s in array)
        yield return s.Trim();
}

Used through:

lines = new List<string>(GetTrimmed(lines)).ToArray();
like image 122
Mir Avatar answered Oct 16 '22 14:10

Mir