Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#: Add Quotes around string in a comma delimited list of strings

Tags:

string

c#

This probably has a simple answer, but I must not have had enough coffee to figure it out on my own:

If I had a comma delimited string such as:

string list = "Fred,Sam,Mike,Sarah"; 

How would get each element and add quotes around it and stick it back in a string like this:

string newList = "'Fred','Sam','Mike','Sarah'"; 

I'm assuming iterating over each one would be a start, but I got stumped after that.

One solution that is ugly:

int number = 0; string newList = ""; foreach (string item in list.Split(new char[] {','})) {     if (number > 0)     {         newList = newList + "," + "'" + item + "'";     }     else     {         newList = "'" + item + "'";     }     number++; } 
like image 748
Bob Wintemberg Avatar asked Oct 31 '08 15:10

Bob Wintemberg


People also ask

What does |= mean in C?

The ' |= ' symbol is the bitwise OR assignment operator.

What is '~' in C programming?

In mathematics, the tilde often represents approximation, especially when used in duplicate, and is sometimes called the "equivalency sign." In regular expressions, the tilde is used as an operator in pattern matching, and in C programming, it is used as a bitwise operator representing a unary negation (i.e., "bitwise ...

What is an operator in C?

C operators are one of the features in C which has symbols that can be used to perform mathematical, relational, bitwise, conditional, or logical manipulations. The C programming language has a lot of built-in operators to perform various tasks as per the need of the program.

What is the use of in C?

In C/C++, the # sign marks preprocessor directives. If you're not familiar with the preprocessor, it works as part of the compilation process, handling includes, macros, and more.


2 Answers

string s = "A,B,C"; string replaced = "'"+s.Replace(",", "','")+"'"; 

Thanks for the comments, I had missed the external quotes.

Of course.. if the source was an empty string, would you want the extra quotes around it or not ? And what if the input was a bunch of whitespaces... ? I mean, to give a 100% complete solution I'd probably ask for a list of unit tests but I hope my gut instinct answered your core question.

Update: A LINQ-based alternative has also been suggested (with the added benefit of using String.Format and therefore not having to worry about leading/trailing quotes):

string list = "Fred,Sam,Mike,Sarah"; string newList = string.Join(",", list.Split(',').Select(x => string.Format("'{0}'", x)).ToList()); 
like image 117
FOR Avatar answered Sep 21 '22 14:09

FOR


Following Jon Skeet's example above, this is what worked for me. I already had a List<String> variable called __messages so this is what I did:

string sep = String.Join(", ", __messages.Select(x => "'" + x + "'")); 
like image 34
vcuankit Avatar answered Sep 20 '22 14:09

vcuankit