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

Viewed 90114

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++;
}
16 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());

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 + "'"));
string[] bits = list.Split(','); // Param arrays are your friend
for (int i=0; i < bits.Length; i++)
{
    bits[i] = "'" + bits[i] + "'";
}
return string.Join(",", bits);

Or you could use LINQ, particularly with a version of String.Join which supports IEnumerable<string>...

return list.Split(',').Select(x => "'" + x + "'").JoinStrings(",");

There's an implementation of JoinStrings elsewhere on SO... I'll have a look for it.

EDIT: Well, there isn't quite the JoinStrings I was thinking of, so here it is:

public static string JoinStrings<T>(this IEnumerable<T> source, 
                                    string separator)
{
    StringBuilder builder = new StringBuilder();
    bool first = true;
    foreach (T element in source)
    {
        if (first)
        {
            first = false;
        }
        else
        {
            builder.Append(separator);
        }
        builder.Append(element);
    }
    return builder.ToString();
}

These days string.Join has a generic overload instead though, so you could just use:

return string.Join(",", list.Split(',').Select(x => $"'{x}'"));
string[] splitList = list.Split(',');
string newList = "'" + string.Join("','", splitList) + "'";

Based off Jon Skeet's example, but modernized for .NET 4+:

// [ "foo", "bar" ] => "\"foo\"", "\"bar\""  
string.Join(", ", strList.Select(x => $"\"{x}\""));

I think the simplest thing would be to Split and then Join.

string nameList = "Fred,Sam,Mike,Sarah";
string[] names = nameList.Split(',');
string quotedNames = "'" + string.Join("','", names) + "'";

I can't write C# code, but this simple JavaScript code is probably easy to adapt:

var s = "Fred,Sam,Mike,Sarah";
alert(s.replace(/\b/g, "'"));

It just replace bounds (start/end of string, transition from word chars non punctuation) by single quote.

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

string[] splitList = list.Split(',');

for (int i = 0; i < splitList.Length; i++)
    splitList[i] = String.Format("'{0}'", splitList[i]);

string newList = String.Join(",", splitList);

The C# implementation of @PhiLho's JavaScript regular expression solution looks something like the following:

Regex regex = new Regex(
    @"\b",
    RegexOptions.ECMAScript
    | RegexOptions.Compiled
    );

string list = "Fred,Sam,Mike,Sarah";
string newList = regex.Replace(list,"'");

My "less sophisticated" approach ... I suppose it's always good practice to use a StringBuilder because the list can be very large.

string list = "Fred,Sam,Mike,Sarah";
StringBuilder sb = new StringBuilder();

string[] listArray = list.Split(new char[] { ',' });

for (int i = 0; i < listArray.Length; i++)
{
    sb.Append("'").Append(listArray[i]).Append("'");
    if (i != (listArray.Length - 1))
        sb.Append(",");
}
string newList = sb.ToString();
Console.WriteLine(newList);

Are you going to be processing a lot of CSV? If so, you should also consider using a library to do this. Don't reinvent the wheel. Unfortunately I haven't found a library quite as simple as Python's CSV library, but I have seen FileHelpers (free) reviewed at MSDN Magazine and it looks pretty good. There are probably other free libraries out there as well. It all depends on how much processing you will be doing though. Often it grows and grows until you realize you would be better off using a library.

Related