Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove whitespaces when storing to an array

Tags:

arrays

c#

trim

Test code:

string files = "C:\Hello; C:\Hi; D:\Goodmorning; D:\Goodafternoon; E:\Goodevening";
string[] paths = files.Split(';');

foreach (string s in paths)
{
    MessageBox.Show(s);
}

How do I remove the whitespaces before storing it into the array?

like image 843
Blackator Avatar asked Sep 04 '12 02:09

Blackator


3 Answers

You can use String.Trim method, like this:

foreach (string s in paths)
{
    MessageBox.Show(s.Trim());
}

Alternatively, you can eliminate spaces before they enter paths, like this:

files.Split(new[]{';', ' '}, StringSplitOptions.RemoveEmptyEntries);
like image 84
Sergey Kalinichenko Avatar answered Nov 09 '22 20:11

Sergey Kalinichenko


.NET 2.0

string[] paths = Array.ConvertAll(files.Split(';'), a => a.Trim());

.NET 3.5

string[] paths = files.Split(';').Select(a => a.Trim()).ToArray();
like image 36
linquize Avatar answered Nov 09 '22 20:11

linquize


Nevermind, I solved it..

My code:

string files = "C:\Hello; C:\Hi; D:\Goodmorning; D:\Goodafternoon; E:\Goodevening";
string[] paths = files.Trim().Split(';');
List<string> cleanPath = new List<string>();

 int x = 0;
 foreach (string s in paths)
 {
     cleanPath.Add(s.Trim());
 }

 foreach(string viewList in cleanPath)
 {
      x++;
      MessageBox.Show(x + ".)" +viewList);//I put x.) just to know whether it still has whitespace characters.
 }
like image 1
Blackator Avatar answered Nov 09 '22 20:11

Blackator