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.
The "Newline in constant" error usually means that somewhere in the code you start a string by opening quotes and then fail to close the quotes.
In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.
The newline character ( \n ) is called an escape sequence, and it forces the cursor to change its position to the beginning of the next line on the screen.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With