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 does not work, because String.Trim returns the version of Trimmed as a new string. And you cannot do line = line.Trim() . So, the only way to do this: the old-school for cycle?

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

Note I am limited to Visual Studio 2005 ie.Net 2.0

+6
source share
4 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(); 
+8
source

According to this , we have a List<string> in .NET 2.0.

So try with List<string> .

 String []lines = System.IO.File.ReadAllLines(path); List<string> yourLinesTrimed = new List<string>; foreach (String line in lines) { yourLinesTrimed.Add(line.Trim()); } 

You can then convert the List<string> to an array using ToArray() .

Create a method that does this:

  public String[] TrimAnArray(String[] lines) { List<string> yourLinesTrimed = new List<string>; foreach (String line in lines) { yourLinesTrimed.Add(line.Trim()); } return yourLinesTrimed.ToArray(); } 
+1
source

"So this is the only way to do this for the old school?" Yes, on .NET 2 you have no Linq stuff. But to be honest, the “old school for the loop” is also the most effective, most readable, and shortest approach. So what is the problem?

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

You can also use LINQ:

 String []lines = System.IO.File.ReadAllLines(path) .Select(line => line.Trim()) .ToArray(); 

EDIT:

If you are limited to .NET 2.0, I would stick with a for-loop, as you did in the second code example. I don’t think there are much better ways to do this, for-loop is quite efficient. Of course, there are some ways to work around LINQ in .NET 2.0, but I don't think it's worth it.

0
source

All Articles