简体   繁体   中英

Unable to handle backslash or escape character in string

Following strings are samples.Strings are coming from response of api.

string s = "string contain another string(< a href =\"https:")";
string text = "This is a \"string\" in C#.";
string text1 = "This is a \na test \nb.";

I want to replace "" with "\" as I want to pass this value to Postgresql.

Only one backslash is not working in postgresql even if column has same value. It worked for double slash '\' or tripple slash'\' from pgadmin or azure data studio.

I am using linq from C# to connect with postgresql.

How to do that

Here in first/second string to introduce string inside string use '' for double quote

-- this code woked fine.

if (s.Contains("\""))
{
    s = s.Replace("\"", "\\\"");
}

-- It is not working
if (s.Contains("\n"))
{
    s = s.Replace("\n", "\\\n");
}

where is I am wrong.

It replace this string ( "This is a \na test \nb."; ) to ( "This is a \\\na test \\\nb."; )

From C# not getting value but when same string I copy and pasted in pgadmin with like statement,it is working.

var result = (from t in DbTestContext.Test
              where t.TestName.Trim().ToLower().Contains(S.Trim().ToLower())
              select new
              {
                  TestStartDate = t.TestStartDate,
              }).FirstOrDefault();

You are wrong where you try to insert a line feed \n into the SQL string. You don't need an actual linefeed there but a backslash flowed by the letter n . So, write:

s = s.Replace("\n", "\\n");

In the first string "\n" there is a "real" linefeed.

The second string is backslash + 'n' in C#. PostgreSQL will interprete this as line feed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM