Remove "\" from string - c#

I've got string from json.
"[{\"Id\":\"1\",\"someOption\":\"2\",\"someText\":\"qweqe\",\"someNumber\":\"123\"},{\"Id\":\"2\",\"someOption\":\"2\",\"someText\":\"qweqw\",\"someNumber\":\"323\"}]"
I want to remove the "\" sign.
Used this for parsing and it didn't work. Debugging shows it's ineffective:
Regex.Replace(json, #"\", "");
and
string signer = json.Replace(#"\", "");
Also Visual Studio shows that pattern #"\"(tried it too in those functions) isn't matching "\" in fact.
I'm confused. Does anyone knows how to create the right pattern here?
I want to retrieve the data later from this match
ex.
[{"id":"1", "someOption":"2", (..) so on}]
Thanks!

You should replace \" by ' . i.e.
string signer = json.Replace("\"", "'");
So, you have:
[{'id':'1', 'someOption':'2', (..) so on}]
Now, you can retrieve the data as you want.
I hope this will be useful.

Language is c#, that escape some characters in string. Char " is one.
This means that the string not contains "\", but you see an escaped string.
In debug, you can see not escaped value in watch by clicking magnifying glass.

Related

C# string format error

I need to send the value I receive from the model with this link, the proposalName field must be in quotes.How can I do it?
Here is my service url.
string path = string.Format("{ProposalId:{proposalId},ProposalName:{"proposalName"},VendorId:{vendorId}}",
Uri.EscapeDataString(proposalId.ToString()),
Uri.EscapeDataString(proposalName),
Uri.EscapeDataString(vendorId.ToString()));
You can simply put quotes around by escaping the quotes, like this -
string path = string.Format("{{0},ProposalName:\"{1}\",VendorId:{2}}",
Uri.EscapeDataString(proposalId.ToString()),
Uri.EscapeDataString(proposalName),
Uri.EscapeDataString(vendorId.ToString()));
As per your updated question, if you need to pass double quotes in URL, you need to encode it to %22
You can also use URI which allows a lot of flexibility with urls. For example -
Uri myUri = new Uri("http://google.com/search?hl=en&q=\"query with quotes\"");
Going with your example - Replace EscapeDataString with Uri.EscapeUriString. It will escape the chracter to form a valid URL. " will get replaced by %22
Some suggestions here and here-
Your problem exactlly in the {"1"} part. The double quotation mark " should be outside the {}, not inside them.
here is the fixed code.
string path = string.Format("{{0},ProposalName:\"{1}\",VendorId:{2}}",
Uri.EscapeDataString(proposalId.ToString()),
Uri.EscapeDataString(proposalName),
Uri.EscapeDataString(vendorId.ToString()));
or
string path = string.Format(#"{{0},ProposalName:""{1}"",VendorId:{2}}",
Uri.EscapeDataString(proposalId.ToString()),
Uri.EscapeDataString(proposalName),
Uri.EscapeDataString(vendorId.ToString()));
and if you are using C# 6 then you can write it as following
string path = $"{Uri.EscapeDataString(proposalId.ToString())},ProposalName:\"{Uri.EscapeDataString(proposalName)}\",VendorId:{Uri.EscapeDataString(vendorId.ToString())}";
This might do the trick for you
\"{1}\"
instead of
{"1"}
because you can put \ symbol to indicate escape sequence followed by a reserved characters
So
string.Format("{{{0},ProposalName:\"{1}\",VendorId:{2}}}",
I think escaping the quotes and placing them outside the brackets will work:
"{{0},ProposalName:\"{1}\",VendorId:{2}}"
Depending on the C# version, you can also do it like this, which I often think is an easier and cleaner way to do it:
string path = $"{proposalId},ProposalName:\"{proposalName}\",VendorId:{vendorId}";
You have two problems:
Wrong quotation (should be outside the braces {...} and escaped)
Incorrect { and } escape: {{ means just a single '{' in a formatting string
Should be
string path = string.Format("{{{0},ProposalName:\"{1}\",VendorId:{2}}}",
please, notice
escaped quotations \" which are outside {1}
tripled curly braces{{{ and }}}
Edit: in your edited question you have the same errors:
string format =
"http://mobile.teklifdosyam.com/VendorReport/GetListProposalService?&page=1&start=0&limit=10&filter=" +
"{{ProposalId:{0},ProposalName:\"{1}\",VendorId:{2}}}";
string path = string.Format(format,
Uri.EscapeDataString(proposalId.ToString()),
Uri.EscapeDataString(proposalName),
Uri.EscapeDataString(vendorId.ToString()));
please, notice escaped quotations \" which are outside the {1}, double '{{' and tripled '}}}'. When formatting you have to use numbers as place holders: so {"proposalName"} must be changed into {0}

String escaping

I want find and replace a substring in a string in C#.
The substring I want to find looks like this:
],\"
and the substring i want to replace looks like this ],\"Name
This is what i tried so far:
string find = #"],\""";
string replace = #"],\""Name";
string newjson = jsonstring.Replace( find, replace );
From your comment
Debugger show me like this "],\\\"Name"
That is the correct output, the debugger is showing you the escaped version of your string. the \\ turns in to a single \ and the \" turns in to a " once the escaping has been applied.
If you click the magnifying glass in the box in your debugger it will open a new window with the escaping applied.
Are you getting any errors when doing what you did?
Otherwise try without using a literal "#"
so something like this:
string find = "],\\\"";
string replace = "],\\\"Name";
string newjson = jsonstring.Replace(find, replace);
Sometime double quotes and string literals still give me issues so I do it that way without using the literal. Hope that helps.

Replace \n by \\n

I have a xml string shown below:
String xml = #"<axislable='ihgyh\nuijh\nkjjfgj'>";
Now when I try to output the xml it shows <axislable='ihgyh\nuijh\nkjjfgj'>
But my requirement is to break the line like below
<axislable='ihgyh
uijh
kjjfgj'>
I have tried replacing the xml using xml = xml.Replace("\n", "\\n"); But it doesnt seems to work.Any ideas how to break the line?
Regards,
Sharmila
Don't use the # prefix:
var xml = "<axislable='ihgyh\nuijh\nkjjfgj'>";
Also you may need "\r\n" instead:
var xml = "<axislable='ihgyh\r\nuijh\r\nkjjfgj'>";
It's not working since you have no line breaks in your string. Your string contains the substring "\n".
Notice you use the # operator.
Try the following:
xml = xml.Replace("\\n", "\n");
Try
xml.Replace(#"\n", Envioroment.NewLine);
Similar to Leo's answer (sorry don't know how to comment on your answer)
String xml = String.Format("<axislable='ihgyh{0}uijh{0}kjjfgj'>", Environment.NewLine);
The # character means that the string is a verbatim string, meaning that escape characters like \n in the string are not processed and treated as text.
The following string is a regular string:
string xml="<axislable='ihgyh\nuijh\nkjjfgj'>";
and translates the \n escape sequence to a newline as you would expect.
You should check the documentation on string literals for the difference between the two forms.

C# Reading a file and writing out replacing string

What I have is a C# windows app that reads a bunch of SQL tables and creates a bunch of queries based on the results. What I'm having a small issue with is the final "," on my query
This is what I have
ColumnX,
from
I need to read the entire file, write out exactly what is in the file and just replace the last , before the from with nothing.
I tried .replace(#",\n\nfrom),(#"\n\nfrom) but it's not finding it. Any help is appreciated.
Example:
ColumnX,
from
Result:
ColumnX
from
The line break is most likely the two character combination CR + LF:
.replace(",\r\n\r\nfrom","\r\n\r\nfrom")
If you want the line break for the current system, you can use the Environment.NewLine constant:
.replace(","+Environment.NewLine+Environment.NewLine+"from",Environment.NewLine+Environment.NewLine+"from")
Note that the # in front of a string means that it doesn't use backslash escape sequences, but on the other hand it can contain line breaks, so you could write it in this somewhat confusing way:
str = str.replace(#",
from", #"
from");
There are two solutions that you can try:
Remove the # symbol, as that means it's going to look for the literal characters of \n rather than a newline.
Try .replace("," + Environment.NewLine + Environment.NewLine + from, Environment.NewLine + Environment.NewLine + "from)
Instead of replacing or removing the comma when you read the file, it would probably be preferable to remove it before the file is written. That way you only have to bother with the logic once. As you are building your column list, just remove the last comma after the list is created. Hopefully you are in a position where you have control over that process.
If you can assume you always want to remove the last occurrence of the comma you can use the string function LastIndexOf to find the index for the last comma and use Remove from there.
myString = myString.Remove(myString.LastIndexOf(","), 1);
What about using Regex? Does that handle different forms of linefeed better?
var result = Regex.Replace(input, #",(\n*)from", "$1from");

.NET string IndexOf unexpected result

A string variable str contains the following somewhere inside it: se\">
I'm trying to find the beginning of it using:
str.IndexOf("se\\\">")
which returns -1
Why isn't it finding the substring?
Note: due to editing the snippet showed 5x \ for a while, the original had 3 in a row.
Your code is in fact searching for 'se\\">'. When searching for strings including backslashes I usually find it easier to use verbatim strings:
str.IndexOf(#"se\"">")
In this case you also have a quote in the search string, so there is still some escaping, but I personally find it easier to read.
Update: my answer was based on the edit that introduced extra slashes in the parameter to the IndexOf call. Based on current version, I would place my bet on str simply not containing the expected character sequence.
Update 2:
Based on the comments on this answer, it seems to be some confusion regarding the role of the '\' character in the strings. When you inspect a string in the Visual Studio debugger, it will be displayed with escaping characters.
So, if you have a text box and type 'c:\' in it, inspecting the Text property in the debugger will show 'c:\\'. An extra backslash is added for escaping purposes. The actual string content is still 'c:\' (which can be verified by checking the Length property of the string; it will be 3, not 4).
If we take the following string (taken from the comment below)
" '<em
class=\"correct_response\">a
night light</em><br
/><br /><table
width=\"100%\"><tr><td
class=\"right\">Ingrid</td></tr></table>')"
...the \" sequences are simply escaped quotation marks; the backslashes are not part of the string content. So, you are in fact looking for 'se">', not 'se\">'. Either of these will work:
str.IndexOf(#"se"">"); // verbatim string; escape quotation mark by doubling it
str.IndexOf("se\">"); // regular string; escape quotation mark using backslash
This works:
string str = "<case\\\">";
int i = str.IndexOf("se\\\">"); // i = 3
Maybe you're not correctly escaping one of the two strings?
EDIT there's an extra couple of \ in the string you are searching for.
Maybe the str variable does not actually contain the backslash.
It may be just that when you mouse over the variable while debugging, the debugger tooltip will show the escape character.
e.g. If you put a breakpoint after this assignment
string str = "123\"456";
the tooltip will show 123\"456 and not 123"456.
However if you click on the visualize icon, you will get the correct string 123"456
Following code:
public static void RunSnippet()
{
string s = File.ReadAllText (#"D:\txt.txt");
Console.WriteLine (s);
int i = s.IndexOf("se\\\">");
Console.WriteLine (i);
}
Gives following output:
some text before se\"> some text after
17
Seems like working to me...
TextBox2.Text = TextBox1.Text.IndexOf("se\"">")
seems to work in VB.
DoubleQuotes within a string need to be specified like "" Also consider using verbatim strings - So an example would be
var source = #"abdefghise\"">jklmon";
Console.WriteLine(source.IndexOf(#"se\"">")); // returns 8
If you are looking for se\">
then
str.IndexOf(#"se\"">")
is less error-prone. Note the double "" and single \
Edit, after the comment: it seems like the string may contain ecaping itself, in which case in se\"> the \" was an escaped quote, so the literal text is simply se"> and the string to use is Indexof("se\">")

Categories

Resources