Trying to convert '' in "" format [duplicate] - c#

I have a string variable such as this:
string title = string.empty;
I have to display the content of whatever is passed to it inside a div within double quotes. I have written something like this:
...
...
<div>"+ title +#"</div>
...
...
How can I add the double quotes here? So that it will display like:
"How to add double quotes"

You need to escape them by doubling them (verbatim string literal):
string str = #"""How to add doublequotes""";
Or with a normal string literal you escape them with a \:
string str = "\"How to add doublequotes\"";

So you are essentially asking how to store doublequotes within a string variable? Two solutions for that:
var string1 = #"""inside quotes""";
var string2 = "\"inside quotes\"";
In order to perhaps make it a bit more clear what happens:
var string1 = #"before ""inside"" after";
var string2 = "before \"inside\" after";

If you have to do this often and you would like this to be cleaner in code, you might like to have an extension method for this.
This is really obvious code, but still I think it can be useful to grab it and make you save time.
/// <summary>
/// Put a string between double quotes.
/// </summary>
/// <param name="value">Value to be put between double quotes ex: foo</param>
/// <returns>double quoted string ex: "foo"</returns>
public static string AddDoubleQuotes(this string value)
{
return "\"" + value + "\"";
}
Then you may call foo.AddDoubleQuotes() or "foo".AddDoubleQuotes(), on every string you like.

If I understand your question properly, maybe you can try this:
string title = string.Format("<div>\"{0}\"</div>", "some text");

You can also include the double quotes into single quotes.
string str = '"' + "How to add doublequotes" + '"';

Another note:
string path = #"H:\\MOVIES\\Battel SHIP\\done-battleship-cd1.avi";
string hh = string.Format("\"{0}\"", path);
Process.Start(#"C:\Program Files (x86)\VideoLAN\VLC\vlc.exe ", hh + " ,--play");
The real value of hh, as passed, will be "H:\MOVIES\Battel SHIP\done-battleship-cd1.avi".
When needing double double literals, use: #"H:\MOVIES\Battel SHIP\done-battleship-cd1.avi";
Instead of: #"H:\MOVIESBattel SHIP\done-battleship-cd1.avi";
Because the first literals is for the path name and then the second literals are for the double quotation marks.

Using string interpolation with a working example:
var title = "Title between quotes";
var string1 = $#"<div>""{title}""</div>"; // Note the order of the $#
Console.WriteLine (string1);
Output
<div>"Title between quotes"</div>

If you want to add double quotes to a string that contains dynamic values also. For the same in place of CodeId[i] and CodeName[i] you can put your dynamic values.
data = "Test ID=" + "\"" + CodeId[i] + "\"" + " Name=" + "\"" + CodeName[i] + "\"" + " Type=\"Test\";

You can use $.
Interpolated Strings:
Used to construct strings. An interpolated string looks like a template string that contains interpolated expressions. An interpolated string returns a string that replaces the interpolated expressions that it contains with their string representations. This feature is available in C# 6 and later versions.
string commentor = $"<span class=\"fa fa-plus\" aria-hidden=\"true\"> {variable}</span>";

You could use " instead of ". It will be displayed correctly by the browser.

Use either
&dquo;
<div>&dquo;"+ title +#"&dquo;</div>
or escape the double quote:
\"
<div>\""+ title +#"\"</div>

In C# you can use:
string1 = #"Your ""Text"" Here";
string2 = "Your \"Text\" Here";

string doubleQuotedPath = string.Format(#"""{0}""",path);

An indirect, but simple to understand alternative to add quotes at start and end of string -
char quote = '"';
string modifiedString = quote + "Original String" + quote;

Put a backslash (\) before the double quotes. That should work.

"<i class=\"fa fa-check-circle\"></i>" is used with ternary operator with Eval() data binding:
Text = '<%# Eval("bqtStatus").ToString()=="Verified" ?
Convert.ToString("<i class=\"fa fa-check-circle\"></i>") :
Convert.ToString("<i class=\"fa fa-info-circle\"></i>"

In C#, if we use "" it means that it will indicate the following symbol is not a C# built-in symbol that will used by the developer.
So in a string we need double quotes, meaning we can put "" symbol before double quotes:
string s = "\"Hi\""

With C# 11.0 preview you can use Raw String Literals.
Raw string literals are a new format for string literals. Raw string literals can contain arbitrary text, including whitespace, new lines, embedded quotes, and other special characters without requiring escape sequences. A raw string literal starts with at least three double-quote (""") characters. It ends with the same number of double-quote characters. Typically, a raw string literal uses three double quotes on a single line to start the string, and three double quotes on a separate line to end the string.
string str = """
"How to add double quotes"
""";

Now with C# 11
var string1 = """before "inside" after""";
var string2 = """ "How to add double quotes" """;

If you want to add double quotes in HTML
echo "<p>Congratulations, “" . $variable . "”!</p>";
Output
Congratulations, "Mr John"!

Related

How to concatenate double quotes with slashes to a string value in c#.net?

How to concatenate double quotes with slashes to a string value?
Expected out put: "\"Hello World\""
Here is my code:
string term="Hello World";
string output = "\"" + term + "\"";
above code result is giving Hello World
Does this help?
string output = "\"\\\"" + term + "\\\"\"";
Live Demo
string output = "\"\\\"" + term + "\\\"\"";
To output quotes and slashes you should use slash before symbols(slash, quotes etc.)
In your case
string term = "Hello World";
string output = "\\\"" + term + "\\\"";
First slash is used to output second slash and third slash used to output quotes.
I don't know whether I should consider first and last quotes in your question or not. If you want to output them just add
\"
You must escape every char, that you want to display.
\"Hello World\":
string output = "\\\"" + term + "\\\"";
"\"Hello World\"":
string output = "\"\\\"" + term + "\\\"\"";
Sure you could add the escape characters yourself, but what if you want to escape values inside the string too? You could write that loop yourself easily enough, or;
public string Escape(string value)
{
using (var writer = new StringWriter())
{
using (var provider = CodeDomProvider.CreateProvider("CSharp"))
{
provider.GenerateCodeFromExpression(new CodePrimitiveExpression(value), writer, null);
return writer.ToString();
}
}
}

How to Replace String In File With Double Quotes

want to Replace Text in My File strText #Insurer with XYZ
output be like this "XYZ"
till now i do this
strText.Replace("#Insurer",XYZ)
this gives me XYZ but not this "XYZ"
so i did this
strText.Replace("\"#Insurer\"",XYZ)
but it didn't replace my String with XYZ
If you want the text after the replacement to be quoted, then you should put the replacement string in quotes:
strText.Replace("#Insurer", "\"" + XYZ + "\"")
Otherwise, you would be searching for the literal string "#Insurer" and just replace it by XYZ. So if there were quotes (which likely isn’t the case, otherwise you wouldn’t want to add them), then this would actually remove them.
Inorder to replace with quotes you can try using backward slash ("\"). The example below shows how to implement.
public string ReplaceString(string strText)
{
string replaceWith = "\"XYZ\"";
string replacedString = strText.Replace("#Insurer", replaceWith);
return replacedString;
}
Add double quote around xyz. You have to escape the double quotes for that you use escape character i.e. backslash \. Also you are not assigning the resultant string back to strText and wont get the changed string.
strText = strText.Replace("#Insurer", "\"" + XYZ + "\"");
The second attempt that failed to replace is because you have added double quotes in string that you are trying to find and there are not double quotes in source string.

Display "" in a string output

I want to display sth like
string test1 = "test2";
so i would like this to be displayed in a richtextbox, but i don't know how to add " in a string output, i have everything working except the displaying of ""; and its C# :) so it should look like that:
string test2 = "test2";
richTextBox.Text = "string test1 = " + (the ") + test2 + (the ") + ";";
You can use backslashes (\) to "escape" a quotation mark. So this string is actually ":
string s = "\"";
Got it? If you still don't, just remember that when ever you want to write a quotation in a string, write \".
So your text would be something like this
richTextBox.Text = "string test1 = \"test2\";";
See? The outer most two quotes denote a string literal and the inner two quotes actually denote the actual quotes in the string. Also, don't forget the semicolon at the end. (You will be likely to forget this because you saw the semi colon in the string literal. But remember! The semicolon is in the string, it's "fake"!)
You have to escape the character " in your string. In C# in many other languages the escape key is \
So your final string will be :
richTextBox.Text = "string test1 = \"" + test2 + "\";";
You can do this by escaping the " like so \":
richTextBox.Text = "string test1 = \"test2\";"
Which will display:
string test1 = "test2";

Finding a string with double quotes

I want this line of code to work-
int start = s.IndexOf(""_type": "Person""name": "");
But clearly the double quotes are messing up the search... Any ideas about how to get this working?
You can take two approaches to this.
The first is by using a string-literal and escaping double-quotes with another double quote:
string s = #"This is a ""quoted"" string.";
s.IndexOf(#"a ""quoted"" string");
The other is to escape the double-quotes with a backslash:
string s = "This is a \"quoted\" string.";
s.IndexOf("a \"quoted\" string");
If you want to use a double-quote in a string, one way is to escape it with a backslash. \
string myString = "This is a string \" with a double quote";
So what you want to do is escape the string? Try this:
int start = s.IndexOf(#"this ""word"" is escaped");
I'm assuming you want to run IndexOf() on the entire string, including the quotes inside? All you have to do is use both types of quotes: ' ' and " ". As long as you use one to designate the main string and the other to designate sub-strings, it should work, i.e. something like: s.IndexOf(' "_type": "Person""name": " ');

Strip double quotes from a string in .NET

I'm trying to match on some inconsistently formatted HTML and need to strip out some double quotes.
Current:
<input type="hidden">
The Goal:
<input type=hidden>
This is wrong because I'm not escaping it properly:
s = s.Replace(""","");
This is wrong because there is not blank character character (to my knowledge):
s = s.Replace('"', '');
What is syntax / escape character combination for replacing double quotes with an empty string?
I think your first line would actually work but I think you need four quotation marks for a string containing a single one (in VB at least):
s = s.Replace("""", "")
for C# you'd have to escape the quotation mark using a backslash:
s = s.Replace("\"", "");
I didn't see my thoughts repeated already, so I will suggest that you look at string.Trim in the Microsoft documentation for C# you can add a character to be trimmed instead of simply trimming empty spaces:
string withQuotes = "\"hellow\"";
string withOutQotes = withQuotes.Trim('"');
should result in withOutQuotes being "hello" instead of ""hello""
s = s.Replace("\"", "");
You need to use the \ to escape the double quote character in a string.
You can use either of these:
s = s.Replace(#"""","");
s = s.Replace("\"","");
...but I do get curious as to why you would want to do that? I thought it was good practice to keep attribute values quoted?
s = s.Replace("\"",string.Empty);
c#: "\"", thus s.Replace("\"", "")
vb/vbs/vb.net: "" thus s.Replace("""", "")
If you only want to strip the quotes from the ends of the string (not the middle), and there is a chance that there can be spaces at either end of the string (i.e. parsing a CSV format file where there is a space after the commas), then you need to call the Trim function twice...for example:
string myStr = " \"sometext\""; //(notice the leading space)
myStr = myStr.Trim('"'); //(would leave the first quote: "sometext)
myStr = myStr.Trim().Trim('"'); //(would get what you want: sometext)
You have to escape the double quote with a backslash.
s = s.Replace("\"","");
s = s.Replace(#"""", "");
This worked for me
//Sentence has quotes
string nameSentence = "Take my name \"Wesley\" out of quotes";
//Get the index before the quotes`enter code here`
int begin = nameSentence.LastIndexOf("name") + "name".Length;
//Get the index after the quotes
int end = nameSentence.LastIndexOf("out");
//Get the part of the string with its quotes
string name = nameSentence.Substring(begin, end - begin);
//Remove its quotes
string newName = name.Replace("\"", "");
//Replace new name (without quotes) within original sentence
string updatedNameSentence = nameSentence.Replace(name, newName);
//Returns "Take my name Wesley out of quotes"
return updatedNameSentence;
s = s.Replace( """", "" )
Two quotes next to each other will function as the intended " character when inside a string.
if you would like to remove a single character i guess it's easier to simply read the arrays and skip that char and return the array. I use it when custom parsing vcard's json.
as it's bad json with "quoted" text identifiers.
Add the below method to a class containing your extension methods.
public static string Remove(this string text, char character)
{
var sb = new StringBuilder();
foreach (char c in text)
{
if (c != character)
sb.Append(c);
}
return sb.ToString();
}
you can then use this extension method:
var text= myString.Remove('"');

Categories