How to Replace String In File With Double Quotes - c#

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.

Related

C# How may i replace \" with "

I am trying to replace \" in a string with ", how may i do that?
I've tried using replace but i could not find a way to do it.
Ex:
string line = "This is a \"sample\" "
string replaced = "This is a "sample" ".
Thanks.
Because quotes are used to start and end strings (they are a type of control character), you can't have a quote in the middle of a string because it would terminate the string
string replaced = "This is a "sample" ";
/*
You can see from the syntax highlighting (red) that the string is being
detected as <This is a > and <sample> is black meaning it is detected as
code (and will cause a syntax error)
*/
In order to put a quote in the middle of the string we escape it (escaping means to treat it as a character literal instead of a control character) using the escape character, which in C# is backslash.
string line = "This is a \"sample\"";
Console.WriteLine(line);
// Output: This is a "sample"
string literalLine = #"This is a ""sample""";
Console.WriteLine(literalLine);
// Output: This is a "sample"
The # symbol in C# means I want this to be a literal string (ignore control characters), however quotes still start and end strings so in order to print a quote in a literal string you write two of them "" (that's how the language is designed)
Case 1: If the value within the variable line is actually This is a \"sample\", then you could do line.Replace("\\\"", "\"").
If not:
\" is an escape sequence. it shows up as \" in the code, however when it compiles it would show up as " instead of the original \".
The reason for escaping quotes is because the compiler cannot identify whether the quote is within another quote or not. Let's see your example:
"This is a "sample" "
is this This is a as one group, then an unknown token sample, then another quote ? or This is a "sample" all within a quote? We can take a guess by looking at the context, but compiler cannot. Hence, we use escape sequence to tell the compiler "I used this double quote character as a character, not the closing/opening of a string literal."
See Also: https://en.wikipedia.org/wiki/Escape_sequences_in_C
You may try something like this:
String str = "This is a \"sample\" ";
Console.WriteLine("Original string: {0}", str);
Console.WriteLine("Replaced: {0}", str.Replace('\"', '"'));
Desired output : This is a sample
Given string : "This is a \"sample\""
The problem: you have escape characters protecting the double quotes from being interpreted. the \ escape character is an instruction to use a quotation mark literally instead of using it to indicate a break in the string. This means the actual string value is "This is a "sample"" when served as output.
The answer removing the \ may work, but it makes for smelly code because removing an escape character in this way can make it unclear what you intend and prevents you from escaping any character.
Removing the " might work, though it prevents use of any quotes and some IDEs might leave the escape character behind to ruin your day.
We want one specific target, the quotes around "sample".
string sample = "This is a \"sample\"";
List<string> sampleArray = sample.Split(' ').ToList(); // samplearray is now split into ["This", "is", "a", "\"sample\""]
var x = sampleArray.FirstOrDefault(t => t == "\"sample\""); //isolate our needed value
if (x != null) //prevent a null reference in case something went wrong and samplearray wasnt as expected
{
var index = sampleArray.IndexOf(x); //get the location of the value we just picked
x = x.Replace("\"", string.Empty); //replace chars
sampleArray[index] = x; //assign new value to the list
}
return String.Join(" ", sampleArray); //return the string joined together with spaces.
Try this:
string line="This is a \"sample\" " ;
replaced =line.Replace(#"\", "");

Trying to convert '' in "" format [duplicate]

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"!

String Manipulation using C#

Using C# we can do string check like if string.contains() method, e.g.:
string test = "Microsoft";
if (test.Contains("i"))
test = test.Replace("i","a");
This is fine. But what if I want to replace a string which contains " symbol to be replaced.
I want to achieve this:
"<html><head>
I want to remove the " symbol present in check so that the result would be:
<html><head>
The " character can also be replaced, just like any other:
test = test.Replace("\"","");
Also, note that you don't have to test if the character exists : your test.Contains("i") could be removed since the .Replace() method won't do anything (no replace, no error thrown) if the character doesn't exist inside the string.
To include a quote symbol in a string, you need to escape it, using a backslash. In your example, you want to use something lik this:
if (test.Contains("\""))
There are two ways to include a '"' character in a string literal. All the answers so far have used the c-style way:
var quotation = "Parting is such sweet sorrow";
var howSweetIsIt = quotation + " that I shall say \"good-night\" till it be morrow.";
In some contexts (especially for users experienced with Visual Basic), the verbatim string literal may be easier to read. A verbatim string literal begins with an # sign, and the only character that requires escaping is the quotation mark -- all other characters are included verbatim (hence the name). Significantly, the method of escaping the quotation mark is different: rather than preceding it with a backslash, it must be doubled:
var howSweetIsIt = quotation + " that I shall say ""good-night"" till it be morrow.";
string SymbolString = "Micro\"so\"ft";
The string above use scape char \ to insert " between the characters
string Result = SymbolString.Replace("\"", string.Empty);
With the following replace I replace the character "" for empty.
This is what you try to achieve?
if (check.Contains("\"")
output = check.Replace("\"", "");
output = check.Replace("\"", "");
Just remember to use "\"" for the quote sign as the backslash is an escape character.
if (str.Contains("\""))
{
str = str.Replace("\"", "");
}

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