proseidon
proseidon

Reputation: 2305

Ignoring commas in a string parsed by commas

So let's say I have a string entering into an Excel document set up like this

output.WriteLine(string.Format("{0},{1},{2},{3}",
                                                   var1,
                                                   var2,
                                                   var3,
                                                   var4
                                                   ));

Now normally it would enter each var into a separate cell. However, I find that if one of my vars has a comma in it, it will treat that as a cell ending, and go to the next one. How can I ignore commas in the vars while maintaining the set up?

Upvotes: 2

Views: 934

Answers (3)

Euphoric
Euphoric

Reputation: 12849

Depends on how you want comas entered. Simplest thing to do:

var1.Replace(",", "string to replace comma for")
var2.Replace(",", "string to replace comma for")
var3.Replace(",", "string to replace comma for")
...

Using list/array and String.Join would make it much easier too.

Upvotes: 1

CodingGorilla
CodingGorilla

Reputation: 19842

I'm assuming this is a CSV file that you're creating. As such you would need to wrap the value that has the comma in it with double quotes. You can either wrap everything (which is easier, like:

output.WriteLine(string.Format("\"{0}\",\"{1}\",\"{2}\",\"{3}\"",
                                                   var1,
                                                   var2,
                                                   var3,
                                                   var4
                                                   ));

Or you could write a small helper function like:

public string EncodeCell(string value) {
   return value.Contains(",") ? String.Format("\"{0}\"", value) : value;
}

And then do:

output.WriteLine(string.Format("{0},{1},{2},{3}",
                                                   EncodeCell(var1),
                                                   EncodeCell(var2),
                                                   EncodeCell(var3),
                                                   EncodeCell(var4)
                                                   ));

Upvotes: 7

juergen d
juergen d

Reputation: 204756

Escape the commas in your vars before inserting with an escape sequence of your choice.

Upvotes: 1

Related Questions