Click here to Skip to main content
15,902,635 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi,

I am using string builder, I want to replace " with \" can anyone help me out...


Ex:

String ex="testing "is" always good";

I Need output as : testing is \" is \" always good

Thanks in advance...
Posted
Updated 25-Mar-11 20:32pm
v2
Comments
Albin Abel 26-Mar-11 4:06am    
How this work String ex="testing "is" always good"; without an escape ?. It throws compiler error.
Ankur\m/ 29-Jun-13 1:57am    
You can create such string using StringBuilder. Convert it to a string and you will see the text like that.
I know the post is too old to reply so was checking out similar posts on web.
Albin Abel 26-Mar-11 4:15am    
or you want the input string like this? string ex=@"testing ""is"" always good";

Try something like:
C#
StringBuilder sb = new StringBuilder();
// to keep double quotes in it, it was escaped by '\'
sb.Append("Some text in here with \"this\" in double quotes");
sb.Replace(@'"', @'\"');



UPDATE:
Based on the updated question, OP needs:
String ex="testing "is" always good";
//I Need output as : testing is \" is \" always good


For this, it sounds like, he wants to have a extra back slash here. No idea why and now I am not going to ask, so try:
C#
StringBuilder sb = new StringBuilder();
// to keep double quotes in it, it was escaped by '\'
sb.Append("Some text in here with \"this\" in double quotes");
sb.Replace(@'"', @'\\"');
 
Share this answer
 
v3
Comments
sathya4260 26-Mar-11 2:30am    
It tried it dude its not working...
Sandeep Mewara 26-Mar-11 2:52am    
Can you elaborate 'not working'?
Sandeep Mewara 26-Mar-11 2:53am    
Did you DEBUG and see that what is the final string formed?
Sandeep Mewara 26-Mar-11 2:56am    
Updated the answer.
[no name] 26-Mar-11 3:00am    
Nice One. My 5 For you Sandeep.
Is this so you can put it into a database? If so, you're doing what they call "escaping" a character, and you need to do this:

C#
StringBuilder sb = new StringBuilder("This is a ""test"" string");
sb.Replace("\"", "\"\"");


If not, I can't think of any reason you'd want to do this, but you need to do this:

C#
StringBuilder sb = new StringBuilder("This is a ""test"" string");
sb.Replace("\"", "\\\"");
 
Share this answer
 
Comments
Ankur\m/ 29-Jun-13 2:05am    
I ran into a similar prolem while creating a JSON string using StringBuilder. First one still doesn't create a valid JSON string (though it will escape quotes making it a valid string) but the second one does.
5!

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