string.Replace does not work for quote - c#

((string)dt.Rows[i][1]).Replace("'", "\\'")
I want the result that if any string have quote it change it into slash quote, e.g. John's -> John\'s
but the above replace function is not working fine.
it results like John\\'s
but if we change the code to
((string)dt.Rows[i][1]).Replace("'", "\'")
it gives the Result like John's
does change it anyway.

Because the backslash is the escape character, you need to tell it you want to treat it like a literal string. You do this by prepending an # to the string:
((string)dt.Rows[i][1]).Replace("'", #"\'")

Try a double backslash.
\\
Just one backslash is an escape; two is an actual backslash.

Use "\\'" or #"\'" for the replacement string. The backslash is the escape character in C# string literals. See the explanation of string literals in C#: \' in a string literal results in just a single quote.
The reason this escape sequence exists, is because single quotes would require escaping if you were using a char literal ('\'').
The # indicates that you're using verbatim string syntax, which allows for multi-line strings and eliminates the need to escape characters, apart from double quote, which you would escape with double double quotes (Visual Basic style).

Can you clarify please? Are you saying that
((string)dt.Rows[i][1]).Replace("'", "\\'")
does not replace a ' with \' ?
Because I just tried it and it works fine. I.e. this
string one = "blah'";
string two = one.Replace("'", "\\'");
Console.WriteLine(two);
Prints blah\'

Replace("'", "\'") use double slash

You could use something like this:
private static string replace(String input)
{
return Regex.Replace(input, "('|\")", "\\'");
}
static void Main(string[] args)
{
String value1 = "John Steve's";
String value2 = "John Steve\"s";
Console.WriteLine(replace(value1));
Console.WriteLine(replace(value2));
}
Results:
John Steve\'s
John Steve\'s

If you want to prepare an SQL query, I think the best method is to replace a single ' for ''. For instance, if you wanto to search John O'Connor, this would work (at least in SQL Server, Access, Oracle, ...).
select ... from users where username = 'Jonh O''Connor'

Related

How can i replace " with \" in C#

Input String is "How are you"
Expected output \"How are you\"
Due to combination of DoubleQuote and escape sequence I am not able to replace the string in the required format.
Please can someone provide me the code snippet for doing this.
I have tried below does not work
myString.Replace(""","\"");
Yes, that looks a little bit weird, you need to escape both:
string test = "\"How are you\"";
test = test.Replace("\"", "\\\"");
Both " and \ have special meaning within a string literal and must be escaped with \.
So something like this:
myString.Replace("\"","\\\"");
Escape your backslash
myString.Replace("\"","\\\"");
This:
"\\\""
produces this:
\"
And also you should escape your double quote in first parameter.
And you can use verbatim strings,but there is a weird case about double quote, instead of \" you should use two double quotes "" to escepe your charachter:
myString.Replace(#"""",#"\""");
string myString = "\"How are you\"";
myString = myString.Replace("\"", "\\\"");

String Manipulation using C#

Using C# we can do string check like if string.contains() method, e.g.:
string test = "Microsoft";
if (test.Contains("i"))
test = test.Replace("i","a");
This is fine. But what if I want to replace a string which contains " symbol to be replaced.
I want to achieve this:
"<html><head>
I want to remove the " symbol present in check so that the result would be:
<html><head>
The " character can also be replaced, just like any other:
test = test.Replace("\"","");
Also, note that you don't have to test if the character exists : your test.Contains("i") could be removed since the .Replace() method won't do anything (no replace, no error thrown) if the character doesn't exist inside the string.
To include a quote symbol in a string, you need to escape it, using a backslash. In your example, you want to use something lik this:
if (test.Contains("\""))
There are two ways to include a '"' character in a string literal. All the answers so far have used the c-style way:
var quotation = "Parting is such sweet sorrow";
var howSweetIsIt = quotation + " that I shall say \"good-night\" till it be morrow.";
In some contexts (especially for users experienced with Visual Basic), the verbatim string literal may be easier to read. A verbatim string literal begins with an # sign, and the only character that requires escaping is the quotation mark -- all other characters are included verbatim (hence the name). Significantly, the method of escaping the quotation mark is different: rather than preceding it with a backslash, it must be doubled:
var howSweetIsIt = quotation + " that I shall say ""good-night"" till it be morrow.";
string SymbolString = "Micro\"so\"ft";
The string above use scape char \ to insert " between the characters
string Result = SymbolString.Replace("\"", string.Empty);
With the following replace I replace the character "" for empty.
This is what you try to achieve?
if (check.Contains("\"")
output = check.Replace("\"", "");
output = check.Replace("\"", "");
Just remember to use "\"" for the quote sign as the backslash is an escape character.
if (str.Contains("\""))
{
str = str.Replace("\"", "");
}

Finding a string with double quotes

I want this line of code to work-
int start = s.IndexOf(""_type": "Person""name": "");
But clearly the double quotes are messing up the search... Any ideas about how to get this working?
You can take two approaches to this.
The first is by using a string-literal and escaping double-quotes with another double quote:
string s = #"This is a ""quoted"" string.";
s.IndexOf(#"a ""quoted"" string");
The other is to escape the double-quotes with a backslash:
string s = "This is a \"quoted\" string.";
s.IndexOf("a \"quoted\" string");
If you want to use a double-quote in a string, one way is to escape it with a backslash. \
string myString = "This is a string \" with a double quote";
So what you want to do is escape the string? Try this:
int start = s.IndexOf(#"this ""word"" is escaped");
I'm assuming you want to run IndexOf() on the entire string, including the quotes inside? All you have to do is use both types of quotes: ' ' and " ". As long as you use one to designate the main string and the other to designate sub-strings, it should work, i.e. something like: s.IndexOf(' "_type": "Person""name": " ');

Double quote string replace in C#

How to replace the below string in C#
Current:
"John K "GEN" Greg"
The Goal:
"John K \"GEN\" Greg"
This is wrong because I'm not escaping it properly:
s = s.Replace(""","\"");
What is syntax for replacing quotes with \ (slash)?
Any help would be appreciated.
Thanks
s = s.Replace("\"", "\\\"");
or
s = s.Replace(#"""", #"\""");
In the first example the " has to be escaped with a backslash as it would otherwise end the string. Likewise, in the replacement string \\ is needed to yield a single backslash by escaping the escape character.
In the second example verbatim string literals are used, they are written as #"...". In those literals no escape sequences are recognized, allowing you to write strings that contain lots of backslashes in a much cleaner way (such as regular expressions). The only escape sequence that works there is "" for a single ".
You should use a double backslash:
s = s.Replace("\"", "\\\"");
To remove ALL quotes from a string, try:
field.Value = Regex.Replace(field.Value, #"[\""]", "", RegexOptions.None);
What a pain trying to find this answer on the internet!
s = s.Replace("\"","\\\"");
What are you escaping it for? If you're going to insert it into DB, consider using prepared statements instead. If you're going to use it in your HTML output, consider using some template engine that does it for yourself instead.
Try: var result = yourString.Replace("\"", "\\\"");
string MailFrom ="aaa#my.web.pk;\"PROMMS\" ccc#my.web.pk;";
string NewMailFrom = Regex.Replace(MailFrom, "\"[^\"]*\"", string.Empty);
Results
aaa#my.web.pk;ccc#my.web.pk;

Unrecognized escape sequence for path string containing backslashes

The following code generates a compiler error about an "unrecognized escape sequence" for each backslash:
string foo = "D:\Projects\Some\Kind\Of\Pathproblem\wuhoo.xml";
I guess I need to escape backslash? How do I do that?
You can either use a double backslash each time
string foo = "D:\\Projects\\Some\\Kind\\Of\\Pathproblem\\wuhoo.xml";
or use the # symbol
string foo = #"D:\Projects\Some\Kind\Of\Pathproblem\wuhoo.xml";
Try this:
string foo = #"D:\Projects\Some\Kind\Of\Pathproblem\wuhoo.xml";
The problem is that in a string, a \ is an escape character. By using the # sign you tell the compiler to ignore the escape characters.
You can also get by with escaping the \:
string foo = "D:\\Projects\\Some\\Kind\\Of\\Pathproblem\\wuhoo.xml";
var foo = #"D:\Projects\Some\Kind\Of\Pathproblem\wuhoo.xml";
If your string is a file path, as in your example, you can also use Unix style file paths:
string foo = "D:/Projects/Some/Kind/Of/Pathproblem/wuhoo.xml";
But the other answers have the more general solutions to string escaping in C#.
string foo = "D:\\Projects\\Some\\Kind\\Of\\Pathproblem\\wuhoo.xml";
This will work, or the previous examples will, too. #"..." means treat everything between the quote marks literally, so you can do
#"Hello
world"
To include a literal newline. I'm more old school and prefer to escape "\" with "\\"

Categories