Reputation: 341
I have a situation in which I want to add inverted commas the the string.
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();
}
As you can see, after converting the Stringbuilder to string, it adds the backslash to the string.
Please help me to know how I can get the desired out as : "AAAA","BBBB", "CCCC"
Upvotes: 1
Views: 3396
Reputation: 17848
Here are the corrected version of your code (fixed enclosing of the first fragments):
string[] strArr = new string[] {
"AAAA", "BBBB","CCCC"
};
StringBuilder sb = new StringBuilder();
for(int i = 0; i < strArr.Length; i++) {
sb.Append('"');
sb.Append(strArr[i]);
sb.Append('"');
if(i < strArr.Length - 1)
sb.Append(',');
}
var output = sb.ToString();
This is how the debugger displays result (quoted/escaped view):
This is how it looks in human-readable format:
"AAAA","BBBB","CCCC"
Tips&tricks:
You can use the nq
format-specifier to display string unquoted/unescaped:
output,nq
Upvotes: 4
Reputation: 955
I think the following code for foreach
loop will solve your problem.
foreach (var value in values)
{
value = "\""+value+"\"";
valueBuilder.Append(value);
if (++valueCounter != valueCount)
{
valueBuilder.Append(@",");
}
}
Upvotes: 0
Reputation: 2296
Just remove valueBuilder.Append("\"");
My mistake. It does just escape the \
Upvotes: -2
Reputation: 1256
The use of quotation marks in a Java String object must be escaped. The \
you are complaining about is only visible in your tool and is required to escape the "
so that no error occurs. If you were to perform a System.out.println(output);
you will not see the \
character.
Upvotes: -1