Click here to Skip to main content
15,908,634 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I have a situation in which I want to add inverted commas the the string.

C#
static void Main(string[] args)
{
    int valueCounter = 0;
    int valueCount = 0;
    var valueBuilder = new StringBuilder();
    List<string> values = new List<string>();
    values.Add("AAAA");
    values.Add("BBBB");
    values.Add("CCCC");
    valueCount = values.Count;

    foreach (var value in values)
    {
        valueCounter++;
        if ((valueCounter - 1) > 0)
            valueBuilder.Append("\"");
        valueBuilder.Append(values[valueCounter - 1].ToString());

        if (valueCounter != valueCount)
        {
            valueBuilder.Append(@",");
        }
    }

    string output = valueBuilder.ToString();

}


valueBuilder gives result as = {AAAA,"BBBB,"CCCC}
output gives result as = "AAAA,"BBBB,\"CCCC"

I want the output as : "AAAA","BBBB", "CCCC"

Please help.
Posted
Comments
Philippe Mori 14-Sep-15 12:57pm    
It look like your code does not match indicated output.

Here's a potentially simpler solution:

C#
int valueCounter = 0;
foreach (var value in values)
{
  valueBuilder.Append('"');
  valueBuilder.Append(values[valueCounter].ToString());
  valueBuilder.Append("\",");
  ++valueCounter;
}

// Remove last comma if the StringBuilder has content.
if (valueBuilder.Length > 0)
  --valueBuilder.Length;
 
Share this answer
 
v2
The problem occurs because you do not add a closing quote to the field that begins with a double quote. So when StringBuilder converts it to a string it tries to escape the floating quote character.

I suspect you are looking at the variables in the debugger, rather than the actual output of your code.

However I suspect your code should be adding quotes after the fields as well as before them like:
C#
if ((valueCounter - 1) > 0)
    valueBuilder.Append("\"");
valueBuilder.Append(values[valueCounter - 1].ToString());
if ((valueCounter - 1) > 0)
    valueBuilder.Append("\"");
 
Share this answer
 
v2
Comments
Philippe Mori 14-Sep-15 12:55pm    
You effectively indicate a problem but the part about escape the floating quote character is wrong... String builder has nothing to do with escaping.
Richard MacCutchan 14-Sep-15 13:19pm    
Quite right, I forgot to update this after running my tests.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900