tags:

views:

6616

answers:

9

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++;
}
+13  A: 
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.

FOR
That simplifies it somewhat. One would just need to add quotes on the beginning and ending of the string to finish it off.
Bob
You'd need to add single quotes to the start and end of the string too.
That would give you"Fred','Sam','Mike','Sarah";
Codewerks
I used it like this, inline: sqlq = sqlq + "AND cc.code in ('" + inpCourseCodes.Text.Replace(",", "','") + "') "); - but I tested first for inpCourseCodes.Text not null.
John Dunagan
+2  A: 
string[] splitList = list.Split(',');
string newList = "'" + string.Join("','", splitList) + "'";
Tor Haugen
I like it for the cleverness, but it's harder to understand (in that it's not as straightforward) as quoting each string and rejoining with commas. Nice anyway though :)
Jon Skeet
+6  A: 
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<string>(this IEnumerable<string> 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();
}
Jon Skeet
+1  A: 

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.

PhiLho
+2  A: 

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) + "'";
Jacob Carpenter
+1  A: 
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);
RickL
A: 

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,"'");
bdukes
Note that this solution fails is the items have spaces in them. In that case, the for loop solution starts to look a lot cleaner.
bdukes
A: 

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);
bruno conde
A: 

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.

Ryan