Home > Back-end >  How to convert a string with one backslash to three backslashes
How to convert a string with one backslash to three backslashes

Time:06-13

I want to convert this string with one backslah:

"{\"PartyCode\":\"99\",\"Name\":\"ooooo\",\"NameEng\":null,\"Note\":null,\"ManagerId\":1,\ParentId\":null,\"PartyStatusId\":1,\"PartyTypeId\":1,\"CenterInfoId\":4177,\"GovernateInfoId\":321,\"LocationInfoId\":25,\"SectorInfoId\":6,\"SectorGroupInfoId\":36,\"SectorCategroyInfoId\":66,\"MainBranch\":null,\"CoordinateX\":null,\"CoordinateY\":null,\"IssueDate\":\"2022-06-08T00: 00:00\"}"

To this string with 3 backslashes:

 "{\\\"PartyCode\\\":\\\"99\\\",\\\"Name\\\":\\\"ooooo\\\",\\\"NameEng\\\":null,\\\"Note\\\":null,\\\"ManagerId\\\":1,\\\"ParentId\\\":null,\\\"PartyStatusId\\\":1,\\\"PartyTypeId\\\":1,\\\"CenterInfoId\\\":4177,\\\"GovernateInfoId\\\":321,\\\"LocationInfoId\\\":25,\\\"SectorInfoId\\\":6,\\\"SectorGroupInfoId\\\":36,\\\"SectorCategroyInfoId\\\":66,\\\"MainBranch\\\":null,\\\"CoordinateX\\\":null,\\\"CoordinateY\\\":null,\\\"IssueDate\\\":\\\"2022-06-08T00: 00:00\\\"}"

I tried .Replace("\\","\\\\\\") but did not work.

CodePudding user response:

The string is immutable creates a new string each time. So you have to reassign new string to the previous variable. Also instead of ("\ \ ", use (" \ " ",

var str = "{\"PartyCode\":\"99\",\"Name\":\"ooooo\",\"NameEng\":null,\"Note\":null,\"ManagerId\":1,\"ParentId\":null,\"PartyStatusId\":1,\"PartyTypeId\":1,\"CenterInfoId\":4177,\"GovernateInfoId\":321,\"LocationInfoId\":25,\"SectorInfoId\":6,\"SectorGroupInfoId\":36,\"SectorCategroyInfoId\":66,\"MainBranch\":null,\"CoordinateX\":null,\"CoordinateY\":null,\"IssueDate\":\"2022-06-08T00: 00:00\"}";

str = str.Replace("\"", "\\\\\\\"");

CodePudding user response:

Your original string is escaping the double quotes.

Your desired string is escaping the double quotes, and escaping the backslash preceeding the double quotes.

So to get your desired string, you need to ensure that you preceed every double quote with a backslash.

You could do that with .Replace(@"""", @"\""").

Also note that your original string is missing a double quote before ParentId.

  • Related