New Line in Constant error

2019-01-17 20:40发布

问题:

I am writing a c# code in which i am fetching values from the database and using it. The problem i am facing is as below.

If my fetched value from the database is :

 string cat1 = "sotheby's";

now while using this cat i want to insert an escape character before single quote, to achieve this i have written the below code:

  string cat1 = "sotheby's";
                    if (cat1.Contains("'")) {
                        var indexofquote = cat1.IndexOf("'");
                        cat1.Insert(indexofquote-1,"\");
                        var cat2 = cat1;
                    }

The error rises in insert line, the backslash(escape character). The error is New Line in Constant. Please help me how to correct this error.

回答1:

You can't just write "\" in C# code. That will produce the "New Line in Constant" error because it 'escapes' the second quote so that it doesn't count. And the string isn't closed.

Use either "\\" (escaping the \ with itself)
or use @"\" (a verbatim string).



回答2:

The Backslash in string literals is an escape character, so it must either be escaped itself:

"\\"

Or you can use a so-called verbatim string literal:

@"\"

See: http://msdn.microsoft.com/en-us/library/aa691090.aspx

Regarding your compile error: The backslash escapes the following quotation mark, thus the string literal is not recognized as closed. The following characters ) and ; are valid for string literals, however the line ending (newline) is not. Hence the error.



回答3:

That will only replace 1 single quote. To get them all use:

string cat1_escaped = cat1.Replace("'", "\'");

Although a lot of databases don't escape quotes like that, but rather by doubling them:

string cat1_escaped = cat1.Replace("'", "''");