Removing spaces when stored in an array

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 to remove spaces before storing in an array?

+4
source share
5 answers

You can use the String.Trim method, for example:

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

Alternatively, you can exclude spaces before they enter paths , for example:

 files.Split(new[]{';', ' '}, StringSplitOptions.RemoveEmptyEntries); 
+9
source

.NET 2.0

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

.NET 3.5

 string[] paths = files.Split(';').Select(a => a.Trim()).ToArray(); 
+4
source

Nevermind, I solved it.

My code is:

 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. } 
+1
source

What about:

string[] paths = Regex.Split(files, @";\W+");

Of course, you also have additional flexibility in RegEx.

0
source

You can use this PHP function: $ var = str_replace ("," ", $ var);

-3
source

Source: https://habr.com/ru/post/1432175/


All Articles