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('"');
Related
My requirement
If string contains single slash (/ or \) it should be replace with
double slash
Note :- string is randomly generated so, I have no control.
e.g. I have string
string str = #"*?i//y\^Pk#t9`n2";
When I tried as
str = str.Replace(#"\", #"\\").Replace(#"/",#"//");
it replaced // with //// but I need to replace only single slash(\) with double slash(\\).
Above code actual result is
*?i////y\^Pk#t9`n2
expected result is
*?i//y\\^Pk#t9`n2
Note :- If string contain double slash in sequence like "//" or "\\" then no need to modify string. but string contains single slash (/ or \) need to replace with double slash.
I have tried to find out other approach then I found following stack-overflow already question-answer
Replace single backslash with double backslash
Replace "\\" with "\" in a string in C#
How to change backslash to double backslash?
Question :-
How to check if string contain single slash and how to replace it?
What best practice should follows while doing string manipulation like this?
Edit :-
I have random generated string comes from user like.
string str = #"*?i//y\^Pk#t9`n2";
sometimes that string contain single slash as above (\). if we consider above string without verbatim(#) it is not a valid string in C#. it gives compile time error. to make above string valid I need to replace "\" with "\\".
How I can achieve this?
Pls try this, first i repleced all double slash with single slash and then vice versa:
var str = #"*?i//y\^Pk#t9`n2";
var tempStr = str.Replace(#"\\", #"\").Replace(#"//",#"/");
var result = tempStr.Replace(#"\", #"\\").Replace(#"/",#"//");
I had to do two Regex.Replace and use look arounds to achieve this. The final solution was
Regex.Replace(Regex.Replace(str, #"(?<!\/)\/(?!\/)", #"//"), #"(?<!\\)\\(?!\\)", #"\\")
If you've never dealt with regex before, it can be a beast. Essentially I am looking for all backslashes and forward slashes (\\ and \/ escaped) and once I match a backslash and forward slash, I am going to use negative lookbehinds and negative aheads to not match if it there is a match in front or behind it.
Negative Look Behind:
(?<!\/)
Negative Look Ahead:
(?!\/)
I am then repeating it twice for forward slashes and backwards slashes
The best solution might be to roll your own algorithm. Step through the string character by character looking for a slash, and if it finds one, check the next character and previous, if 1 of those exist, then do not insert a duplicate slash because that means it is not alone
This replaces all of the individual occurrences of a character and also fills up an odd number of occurrences:
public static string ReplaceSingle(this string s, char needle)
{
var valueSpan = s.AsSpan();
var length = valueSpan.Length * 2;
char[]? resultArray = null;
Span<char> resultSpan = length <= 256
? stackalloc char[length]
: (resultArray = ArrayPool<char>.Shared.Rent(length));
var value = char.MinValue;
var written = 0;
for (int index = 0; index < valueSpan.Length; index++)
{
value = valueSpan[index];
resultSpan[written++] = value;
if (value == needle && ++index < valueSpan.Length)
{
value = valueSpan[index];
resultSpan[written++] = value == needle ? value : needle;
}
}
var result = new string(resultSpan[..written]);
resultSpan.Clear();
if (resultArray is not null) ArrayPool<char>.Shared.Return(resultArray);
return result;
}
For instance, if you have / it will turn to //, but // will remain. However /// will turn to //// and so on.
There is also a usage of ArrayPool and stackalloc which are aimed at better performance.
Usage:
string value = "This/ is a //Test ///!";
string result = value.ReplaceSingle('/');
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("\"", "");
}
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": " ');
Assume I have a string "2.36" and I want it trimmed to "236"
I used Trim function in example
String amount = "2.36";
String trimmedAmount = amount.Trim('.');
The value of trimmedAmount is still 2.36
When amount.Trim('6'); it works perfectly but with '.'
What I am doing wrong?
Thanks a lot
Cheers
Trimming is removing characters from the start or end of a string.
You are simply trying to remove the ., which can be done by replacing that character with nothing:
string cleanAmount = amount.Replace(".", string.Empty);
If you want to remove everything but the digits:
String trimmedAmount = new String(amount.Where(Char.IsDigit).ToArray());
or:
String trimmedAmount = Regex.Replace(amount, #"\D+", String.Empty);
String.Trim removes leading and trailing whitespace. You need to use String.Replace()
Like:
string amount = "2.36";
string newAmount = amount.Replace(".", "");
Two ways :
string sRaw = "5.32";
string sClean = sRaw.Replace(".", "");
Trim is make for removing leading and trailings characters (such as space by default).
How do I replace \n with empty space?
I get an empty literal error if I do this:
string temp = mystring.Replace('\n', '');
String.Replace('\n', '') doesn't work because '' is not a valid character literal.
If you use the String.Replace(string, string) override, it should work.
string temp = mystring.Replace("\n", "");
As replacing "\n" with "" doesn't give you the result that you want, that means that what you should replace is actually not "\n", but some other character combination.
One possibility is that what you should replace is the "\r\n" character combination, which is the newline code in a Windows system. If you replace only the "\n" (line feed) character it will leave the "\r" (carriage return) character, which still may be interpreted as a line break, depending on how you display the string.
If the source of the string is system specific you should use that specific string, otherwise you should use Environment.NewLine to get the newline character combination for the current system.
string temp = mystring.Replace("\r\n", string.Empty);
or:
string temp = mystring.Replace(Environment.NewLine, string.Empty);
This should work.
string temp = mystring.Replace("\n", "");
Are you sure there are actual \n new lines in your original string?
string temp = mystring.Replace("\n", string.Empty).Replace("\r", string.Empty);
Obviously, this removes both '\n' and '\r' and is as simple as I know how to do it.
If you use
string temp = mystring.Replace("\r\n", "").Replace("\n", "");
then you won't have to worry about where your string is coming from.
One caveat: in .NET the linefeed is "\r\n". So if you're loading your text from a file, you might have to use that instead of just "\n"
edit> as samuel pointed out in the comments, "\r\n" is not .NET specific, but is windows specific.
What about creating an Extension Method like this....
public static string ReplaceTHAT(this string s)
{
return s.Replace("\n\r", "");
}
And then when you want to replace that wherever you want you can do this.
s.ReplaceTHAT();
Best Regards!
Here is your exact answer...
const char LineFeed = '\n'; // #10
string temp = new System.Text.RegularExpressions.Regex(
LineFeed
).Replace(mystring, string.Empty);
But this one is much better... Specially if you are trying to split the lines (you may also use it with Split)
const char CarriageReturn = '\r'; // #13
const char LineFeed = '\n'; // #10
string temp = new System.Text.RegularExpressions.Regex(
string.Format("{0}?{1}", CarriageReturn, LineFeed)
).Replace(mystring, string.Empty);
string temp = mystring.Replace("\n", " ");
#gnomixa - What do you mean in your comment about not achieving anything? The following works for me in VS2005.
If your goal is to remove the newline characters, thereby shortening the string, look at this:
string originalStringWithNewline = "12\n345"; // length is 6
System.Diagnostics.Debug.Assert(originalStringWithNewline.Length == 6);
string newStringWithoutNewline = originalStringWithNewline.Replace("\n", ""); // new length is 5
System.Diagnostics.Debug.Assert(newStringWithoutNewline.Length == 5);
If your goal is to replace the newline characters with a space character, leaving the string length the same, look at this example:
string originalStringWithNewline = "12\n345"; // length is 6
System.Diagnostics.Debug.Assert(originalStringWithNewline.Length == 6);
string newStringWithoutNewline = originalStringWithNewline.Replace("\n", " "); // new length is still 6
System.Diagnostics.Debug.Assert(newStringWithoutNewline.Length == 6);
And you have to replace single-character strings instead of characters because '' is not a valid character to be passed to Replace(string,char)
I know this is an old post but I'd like to add my method.
public static string Replace(string text, string[] toReplace, string replaceWith)
{
foreach (string str in toReplace)
text = text.Replace(str, replaceWith);
return text;
}
Example usage:
string newText = Replace("This is an \r\n \n an example.", new string[] { "\r\n", "\n" }, "");
Found on Bytes.com:
string temp = mystring.Replace('\n', '\0');// '\0' represents an empty char