Execute Trim () when using Split ()

Today I was wondering if there is a better solution to execute the following code example.

string keyword = " abc, foo , bar"; string match = "foo"; string[] split= keyword.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries); foreach(string s in split) { if(s.Trim() == match){// asjdklasd; break;} } 

Is there a way to execute trim () without manually repeating each element? I am looking for something like "split by the following characters and automatically crop every result."

Ah, right before the publication I found

 List<string> parts = line.Split(';').Select(p => p.Trim()).ToList(); 

in How can I split and trim a string into pieces on the same string?

Nevertheless, I am curious: maybe there is a better solution? (Or does the compiler possibly convert them to the same code output as Linq-Operation?)

+41
string c # trim
Dec 29 '09 at 10:30
source share
6 answers

Another possible option (which avoids LINQ, for better or worse):

 string line = " abc, foo , bar"; string[] parts= Array.ConvertAll(line.Split(','), p => p.Trim()); 

However, if you just need to know if there is - maybe a short circuit?

 bool contains = line.Split(',').Any(p => p.Trim() == match); 
+67
Dec 29 '09 at 22:33
source share
— -

I would suggest using regular expressions in the source string, looking for the pattern "any number of spaces followed by one of your delimiters, followed by one or more spaces", and remove these spaces. Then split.

+3
Dec 29 '09 at 22:35
source share

Try the following:

 string keyword = " abc, foo , bar"; string match = "foo"; string[] split = Regex.Split(keyword.Trim(), @"\s*[,;]\s*"); if (split.Contains(match)) { // do stuff } 
+3
Dec 29 '09 at 22:48
source share

If spaces just surround the words with a comma, this will work:

 var keyword = " abc, foo , bar"; var array = keyword.Replace(" ", "").Split(','); if (array.Contains("foo")) { Debug.Print("Match"); } 
+3
Dec 29 '09 at 22:51
source share

You will find many different ways to do this, and changes in performance and accuracy will not be apparent. I would recommend connecting them all to a test suite, such as NUnit, to find which one comes out on top and which ones are accurate.

Use small, medium, and large amounts of text in loops to explore different situations.

+1
Dec 29 '09 at 22:43
source share
 var parts = line.Split(';').Select(p => p.Trim()).Where(p => !string.IsNullOrWhiteSpace(p)).ToArray(); 
+1
Sep 22 '14 at 9:00
source share



All Articles