How to easily display double quotes in strings in C#? - c#

If you have a string with a numerous double quotes,
in PHP you can do this:
file.WriteLine('<controls:FormField Name="Strasse" LabelText="Strasse">');
in C# you have to do this:
file.WriteLine("<controls:FormField Name=\"Strasse\" LabelText=\"Strasse\">");
Is there a way in C# to do what you can do above in PHP, something like the #"c:\temp" which you can do so that you don't need double slashes?
Thanks Fredrik, that makes even quotes and curly brackets in a String.Format fairly readable:
file.WriteLine(String.Format(#"<TextBox Text=""{{Binding {0}}}""
Style=""{{DynamicResource FormularFieldTextBox}}""/>", fieldName));

There are two ways to represent quotes in C# strings:
file.WriteLine("<controls:FormField Name=\"Strasse\" LabelText=\"Strasse\">");
file.WriteLine(#"<controls:FormField Name=""Strasse"" LabelText=""Strasse"">");

"<controls:FormField Name='Strasse' LabelText='Strasse'>".Replace("'", "\"")
Which isn't great, but about the only option.
Or #"""" insted of \" you can use ""

I would recommend avoiding some bizarre way like this:
const char doubleQuote = '"';
Console.WriteLine("<controls:FormField Name={0}Strasse{0} LabelText={0}Strasse{0}>", doubleQuote);

I would recommend using a resource file to store the string constants.
This increases elegance and code readability.
Also, quotes and special characters can be displayed without messing around with too many escape sequences.
You can create a resource file entry like,
String Name(Key) => FormFieldControl
Value => <controls:FormField Name="{0}" LabelText="{1}">
This can be used in code like
const string fieldName = "Strasse";
Console.WriteLine(ResourceFile.FormFieldControl, fieldName, fieldName);

Related

Any way to use string (without escaping manually) that contains double quotes

Let's say I want to assign a text (which contains many double quotes) into variable. However, the only way seems to manually escape:
string t = "Lorem \"Ipsum\" dummy......
//or//
string t = #"Lorem ""Ipsum"" dummy.....
Is there any way to avoid manual escaping, and instead use something universal (which I dont know in C#) keywoard/method to do that automatically? In PHP, it's untoldly simple, by just using single quote:
$t = 'Lorem "Ipsum" dummy .......
btw, please don't bomb me with critiques "Why do you need to use that" or etc. I need answer to the question what I ask.
I know this answer may not be satisfying, but C# sytnax simply won't allow you to do such thing (at the time of writing this answer).
I think the best solution is to use resources. Adding/removing and using strings from resources is super easy:
internal class Program
{
private static void Main(string[] args)
{
string myStringVariable = Strings.MyString;
Console.WriteLine(myStringVariable);
}
}
The Strings is the name of the resources file without the extension (resx):
MyString is the name of your string in the resources file:
I may be wrong, but I conjecture this is the simplest solution.
No. In C# syntax, the only way to define string literals is the use of the double quote " with optional modifiers # and/or $ in front. The single quote is the character literal delimiter, and cannot be used in the way PHP would allow - in any version, including the current 8.0.
Note that the PHP approach suffers from the need to escape ' as well, which is, especially in the English language, frequently used as the apostrophe.
To back that up, the EBNF of the string literal in current C# is still this:
regular_string_literal '"' { regular_string_literal_character } '"'
The only change in the compiler in version 8.0 was that now, the order of the prefix modifiers $ (interpolated) and # (verbatim) can be either #$ or $#; it used to matter annoyingly in earlier versions.
Alternatives:
Save it to a file and use File.ReadAllText for the assignment, or embed it as a managed ressource, then the compiler will provide a variable in the namespace of your choice with the verbatim text as its runtime value.
Or use single quotes (or any other special character of your choice), and go
var t = #"Text with 'many quotes' inside".Replace("'", #"""");
where the Replace part could be modeled as an extension to the String class for brevity.

"Evaluate" a c# string

I am reading a C# source file.
When I encounter a string, I want to get it's value.
For instance, in the following example:
public class MyClass
{
public MyClass()
{
string fileName = "C:\\Temp\\A Weird\"FileName";
}
}
I would like to retrieve
C:\Temp\A Weird"FileName
Is there an existing procedure to do that?
Coding a solution with all the possible cases should be quite tricky (#, escape sequences. ...).
I am convinced such procedure exists...
I would like to have the dual function too (to inject a string into a C# source file)
Thanks in advance.
Philippe
P.S:
I gave an example with a filename, but I look for a solution working for all kinds of strings.
I'm pretty sure you can use CodeDOM to read a C# code file and parse its elements. It generates a code tree, and then you can look for nodes representing strings.
http://www.codeproject.com/Articles/2502/C-CodeDOM-parser
Other CodeDom parsers:
http://www.codeproject.com/Articles/14383/An-Expression-Parser-for-CodeDom
NRefactory: https://github.com/icsharpcode/NRefactory and http://www.codeproject.com/Articles/408663/Using-NRefactory-for-analyzing-Csharp-code
There is a way of extracting these strings using a regular expression:
("(\\"|[^"])*")
This particular one works on your simple example and gives the filename (complete with leading and trailing quote characters); whether it would work on more complex ones I can't easily tell unfortunately.
For clarity, (\\"|[^"]) matches any character apart from ", except where it has a leading \ character.
Just use ".*" Regex to match all string values, then remove trailing inverted commas and unescape it.
this will allow \" and "" characters inside your string
so both "C:\\Temp\\A Weird\"FileName" and "Hello ""World""" will match

escape double quotes inside string literal in C#

i need a regex in c# that will escape double quotes inside string literal. so if i have this string: "How about "this" and how about "that"". i will be able to use it in javascript without errors. because i am writing this literal to the page as js var.
EDIT: i will try to explain more about the problem.
i writing messege to the page like this:
string UserMsg = GetMessageText(999);
StringBuilder script = new StringBuilder();
script.AppendFormat("var UserMsg =\"{0}\";{1}", UserMsg, Environment.NewLine);
ScriptManager.RegisterClientScriptBlock(this, GetType(), "scriptparams", script.ToString(),true);
now lets say messege 999 is this: "we found a "problem" in your details".
this is causing js errors.
You should not use regular expressions to escape your C# strings into a JavaScript friendly / safe format. Instead, assuming you are using .NET 4, you can use HttpUtility.JavaScriptStringEncode and it's overload to take care of both single and double quotes for you.
For example:
string UserMsg = GetMessageText(999);
StringBuilder script = new StringBuilder();
script.AppendFormat("var UserMsg =\"{0}\";{1}", HttpUtility.JavaScriptStringEncode(UserMsg), Environment.NewLine);
ScriptManager.RegisterClientScriptBlock(this, GetType(), "scriptparams", script.ToString(),true);
Would ouput the following with UserMsgset to "we found a "problem" in your details":
var UserMsg ="we found a \"problem\" in your details";
Assuming I understand you correctly, to escape a " in C# source code, you can do it like this:
"\""
or
#""""
Either of those literals defines a string containing single double quote character.
On the other hand perhaps you need to know how to escape the quote character in Javascript. That is done with \". You can use String.Replace() to effect that but you would be much better off with a proper HTML/JS emitter library.
See the Web Protection Library (also known as AntiXSS). That has a JavascriptEncode method to do this and other escapes.
Here is my suggestion for you:
var regex = new Regex("\"");
var result = regex.Replace(stringToReplace, "\\\"");
I believe something like this may work:
Regex.Replace(myString,'"',"");
I think your question has been answered already but if you still need the complete code.
below piece of javascript would work for you.
var s = "this is \"Hi \" ";
alert(s);
Praveen

How can I replace "/" with "\/" in a string?

I would like to do the following:
if (string.Contains("/"))
{
string.Replace("/", "\/"); //this isn't valid
}
I've tried
string.Replace("/", "\\/");
but this gives me what I started with. How can I do this?
Thanks
Strings are immutable, which means that any modification you do to a string results in a new one, you should assign the result of the Replace method:
if (myString.Contains("/"))
{
myString = myString.Replace("/", "\\/");
}
String.Replace returns the string with replacements made - it doesn't change the string itself. It can't; strings are immutable. You need something like:
text = text.Replace("/", "\\/");
(In future examples, it would be helpful if you could use valid variable names btw. It means that those wishing to respond with working code can use the same names as you've used.)
One way is to use a verbatim string literal
string.Replace("/", #"\");

Most readable way to assign a double quote to a string in C#

Does anyone else think that escaping characters in very short strings make them not very readable? I noticed I was using s = "\"" in my code to assign a double quote a string, but having thought about it, I came up with the following alternative: s = '"'.ToString().
Is my alternative any good? Would you prefer see the first version in code?
How would you go about assigning two double quotes (""), which might be s = "\"\"", to a string?
/me is marking this CW before being pressured into it.
You could use:
String s = new String('"', 1);
or if you like to confuse people:
String s = #"""";
but actually I still prefer the good-old-fashioned escape: \"
I'm not sure the alternative is more readable, on the contrary it's confusing. Besides, using a function call to have a different look in the source code doesn't make much sense - I would even say it's bad practice.
The old-fashioned escape sequence is the best option IMHO.

Categories