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.
Related
I am working with C#. I had a string which was in the format:
myString = ""Person:Name","Address:City","University:District""
I know having quotes within a main string quote is not right in C# and that you have to escape quotes. But this string that I have here is the result of concatenation of several strings to make it look like that for some back-end processing.It was a string list of the format [A:B, C:D, E:F] which was converted into JSON format and then back to string again. I stripped off the external brackets already in case you're wondering. So before moving further, I'd like to clarify that this is a legal string and the quotes within the string are not a problem in this particular scenario.
I want my final output to display in multiple lines like the following:
Person:Name
Address:City
University:District
I tried to achieve it by doing the following:
myString = myString.Replace(',', '\n'); //replaced comma with newline
myString = myString.Replace('"', ' '); //replaced double quote with a space
I have them in separate lines now, however my problem now is I can't seem to get rid of the space. I want all of the spaces removed. i.e 6 total below. Turns out Trim() does not help me. Is there a way to solve this? This is where I am at right now. I'm open to trying any new idea if my way is not correct. If you're confused with the way the string is, you can ask me.
(space)Person:Name(space)
(space)Address:City(space)
(space)University:District(space)
You are replacing double quotes with a space here.
myString = myString.Replace('"', ' ');
It should be like this :
myString = myString.Replace('"', '');
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}
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.
I want to use \ in a string, like
string str="abc\xyz";
But this is giving me error.
I have also tried
string str="abc\\xyz";
But still it isnt working.
Can anyone help me out?
You can either escape the character, like so:
string str="abc\\xyz";
or use a verbatim string literal like so:
string str=#"abc\xyz";
So your second example should work.
See here for more information.
Well, the latter ("abc\\xyz") will certainly result in a backslash in the string - or you could use a verbatim string literal:
string str = #"abc\xyz";
Note that if you use the debugger to look at your strings, it will often (always?) "escape" them for you, so you'd see "abc\\xyz". This can cause a fair amount of confusion. Either look at the characters individually, or print the string to the console.
You haven't said in what way it "isn't working" - could you give more details? If it's just the debugger output, then the above may be all you're looking for - but otherwise you should tell us what you're seeing vs what you expected to see.
Have a look at my article about strings for more information about strings in general, escaping, the debugger etc.
string str="abc\\xyz";
Normally, this should work. An alternative is:
string str = #"abc\xyz";
public class Program
{
static void Main(string[] args)
{
string str = "abc\\xyz";
Console.WriteLine(str);
}
}
This works fine. It prints abc\xyz.
You can do it like this
string str = #"abc\xyz";
string str = #"abc\xyz";
You can do this:
string str = #"abc\xyz";
That tells says that the slash is significant and not an escape character.
You'll need to prefix the string with the '#' symbol to stop the compiler trying to treat it as an escape sequence. So string str = #"abc\xyz"; should work.
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\">")