Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing extra commas from string after using String.Join to convert array to string (C#)

Tags:

string

c#

join

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?

like image 329
Chris Avatar asked Oct 07 '10 12:10

Chris


People also ask

How do you join an array without commas?

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.

How do you remove commas from an array?

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.

How do you remove commas from Tostring?

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.

How do you get a comma separated string from an array in C?

Declare an array of strings. Use the string join() function to get the comma separated strings.


2 Answers

Try this :):

var res = string.Join(",", array.Where(s => !string.IsNullOrEmpty(s))); 

This will join only the strings which is not null or "".

like image 149
Lasse Espeholt Avatar answered Sep 18 '22 22:09

Lasse Espeholt


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))); 
like image 22
bernhof Avatar answered Sep 19 '22 22:09

bernhof