I'm converting an array into a string using String.Join
. A small issue I have is that, in the array some index positions will be blank. An example is below:
array[1] = "Firstcolumn" array[3] = "Thirdcolumn"
By using String.Join(",", array);, I'll get the following:
Firstcolumn,,Thirdcolumn
Note the extra ,.
How can I remove the extra commas from the string, or ideally not include blank indices when using String.Join?
To convert an array to a string without commas, call the join() method on the array, passing it an empty string as a parameter - arr. join('') . The join method returns a string containing all array elements joined by the provided separator.
You can use the join() method in JavaScript to remove commas from an array. The comma delimiter in an array works as the separator. For example, let arr = ['alpha', 'bravo', 'charlie']. Using the join() method, you can remove or replace all the commas with a space.
To remove all commas from a string, call the replace() method, passing it a regular expression to match all commas as the first parameter and an empty string as the second parameter. The replace method will return a new string with all of the commas removed.
Declare an array of strings. Use the string join() function to get the comma separated strings.
Try this :):
var res = string.Join(",", array.Where(s => !string.IsNullOrEmpty(s)));
This will join only the strings which is not null
or ""
.
A simple solution would be to use linq, by filtering out the empty items before joining.
// .net 3.5 string.Join(",", array.Where(item => !string.IsNullOrEmpty(item)).ToArray());
In .NET 4.0 you could also make use of string.IsNullOrWhiteSpace
if you also want to filter out the items that are blank or consist of white space characters only (note that in .NET 4.0 you don't have to call ToArray
in this case):
// .net 4.0 string.Join(",", array.Where(item => !string.IsNullOrWhiteSpace(item)));
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