Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any better way to TRIM() after string.Split()?

Tags:

c#

.net

Noticed some code such as

string[] ary = parms.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
for( int i = 0; i < ary.Length; i++)
       ary[i] = ary[i].Trim();

works fine but wondering if there is a better way to do this in one step

like image 847
Kumar Avatar asked Dec 09 '11 19:12

Kumar


People also ask

How do you use split and trim together?

Split and Trim String input = " car , jeep, scooter "; To remove extra spaces before and/or after the delimiter, we can perform split and trim using regex: String[] splitted = input. trim().

How do you get rid of space after a split?

To split the sentences by comma, use split(). For removing surrounding spaces, use trim().

How split a string after a specific character in C#?

Split(char[], StringSplitOptions) Method This method is used to splits a string into substrings based on the characters in an array. You can specify whether the substrings include empty array elements. Syntax: public String[] Split(char[] separator, StringSplitOptions option);

How do you split a string after?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


2 Answers

string[] trimmedStrings = parms.Split(',')
                               .Select(s => s.Trim())
                               .Where(s => s != String.Empty)
                               .ToArray();

BTW, consider using generic typed list like List<string> rather than legacy arrays

IList<string> trimmedStrings = parms.Split(',')
                                    .Select(s => s.Trim())
                                    .Where(s => s != String.Empty)
                                    .ToList();
like image 54
sll Avatar answered Oct 13 '22 09:10

sll


Still 2 steps but without the loop

ary = ary.Select(str => str.Trim()).ToArray();

or

ary = ary.Split(',').Select(str => str.Trim())
                    .Where(str => str != string.Empty)
                    .ToArray();

To preserve the RemoveEmptyEntries behavior and also remove the items that are trimable

like image 31
vc 74 Avatar answered Oct 13 '22 09:10

vc 74