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("\"", "");
}
Related
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(#"\", "");
i am using a web service and result is coming like this
" methew wade watto"
then I've tried with string.replace():
jsona = jsona.Replace(#"", "");
but the problem is i am unable to replace special character's like " this in my replace statement, How can I replace " from the input string? and what are the other options of replacing the string other then this?
In c#, The # symbol means to read that string literally, and don't
interpret control characters otherwise. whereas \ followed by a
character that is not recognized as an escaped character, matches that
character.
So you have to use \" to represent " in .Replace() instead for #
I think you have to try something like this:
string jsonInput = "\"methew wade watto\""; // be the input
string replacedQuotes = jsonInput.Replace("\"", "");
Working example
You need to escape the " with \ , right now, you are just saying to replace empty string with empty string:
jsona= jsona.Replace("\"","");
Now this will replace the " sign in your string with empty string.
Output:
methew wade watto
Use a backslash to determine special character
string = string.Replace("\"", "");
I have a string that contains sequence of three "\" and I have to replace them with single "\".
the string is:
string sample = "<ArrayOfMyObject xmlns:i=\\\"http://www.w3.org/2001/XMLSchema-instance\\\"";
I have tried, as suggested in other threads, with the following code but it did not work:
string result = sample.Replace(#"\\\",#"\");
string result = sample.Replace("\\\\\\","\\");
thanks in advance
In your sample, your string doesn't actually have three "\" characters in it - Some of them are escape characters.
\ will actually correspond to a single \ character.
\" will actually correspond to a single " character.
The value of your string, in memory, is:-
<ArrayOfMyObject xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"
So, your replace operations do nothing because they do not match anything.
To replace \\\ with \ in a c# string try this code (tested and working)
string strRegex = #"(\\){3}";
string strTargetString = #"sett\\\abc";
var test=Regex.Replace(strTargetString, strRegex, #"\"); //test becomes sett\abc
in debug you will see test=sett\\abc (2 backslashes but one is an escape).
Don't worry and go to text Visualizer and you'll see the correct value
then
in your specific case the code will be
string sample = #"<ArrayOfMyObject xmlns:i=\\\"http://www.w3.org/2001/XMLSchema-instance\\\"";
var result=Regex.Replace(sample , strRegex, #"\");
the output of both of the replaces is
<ArrayOfMyObject xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"
this looks correct
but maybe you have to add 6 instead of 3 '\' in your input, because there caracters are escape characters.
Input String is "How are you"
Expected output \"How are you\"
Due to combination of DoubleQuote and escape sequence I am not able to replace the string in the required format.
Please can someone provide me the code snippet for doing this.
I have tried below does not work
myString.Replace(""","\"");
Yes, that looks a little bit weird, you need to escape both:
string test = "\"How are you\"";
test = test.Replace("\"", "\\\"");
Both " and \ have special meaning within a string literal and must be escaped with \.
So something like this:
myString.Replace("\"","\\\"");
Escape your backslash
myString.Replace("\"","\\\"");
This:
"\\\""
produces this:
\"
And also you should escape your double quote in first parameter.
And you can use verbatim strings,but there is a weird case about double quote, instead of \" you should use two double quotes "" to escepe your charachter:
myString.Replace(#"""",#"\""");
string myString = "\"How are you\"";
myString = myString.Replace("\"", "\\\"");
How to replace the below string in C#
Current:
"John K "GEN" Greg"
The Goal:
"John K \"GEN\" Greg"
This is wrong because I'm not escaping it properly:
s = s.Replace(""","\"");
What is syntax for replacing quotes with \ (slash)?
Any help would be appreciated.
Thanks
s = s.Replace("\"", "\\\"");
or
s = s.Replace(#"""", #"\""");
In the first example the " has to be escaped with a backslash as it would otherwise end the string. Likewise, in the replacement string \\ is needed to yield a single backslash by escaping the escape character.
In the second example verbatim string literals are used, they are written as #"...". In those literals no escape sequences are recognized, allowing you to write strings that contain lots of backslashes in a much cleaner way (such as regular expressions). The only escape sequence that works there is "" for a single ".
You should use a double backslash:
s = s.Replace("\"", "\\\"");
To remove ALL quotes from a string, try:
field.Value = Regex.Replace(field.Value, #"[\""]", "", RegexOptions.None);
What a pain trying to find this answer on the internet!
s = s.Replace("\"","\\\"");
What are you escaping it for? If you're going to insert it into DB, consider using prepared statements instead. If you're going to use it in your HTML output, consider using some template engine that does it for yourself instead.
Try: var result = yourString.Replace("\"", "\\\"");
string MailFrom ="aaa#my.web.pk;\"PROMMS\" ccc#my.web.pk;";
string NewMailFrom = Regex.Replace(MailFrom, "\"[^\"]*\"", string.Empty);
Results
aaa#my.web.pk;ccc#my.web.pk;