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
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().
To split the sentences by comma, use split(). For removing surrounding spaces, use trim().
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);
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.
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();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With