-1

This code that I found in an answer works perfectly for the characters that I wish to remove from a string.

var str = "My name @is ,Wan.;'; Wan";
var charsToRemove = new string[] { "[", "]" };
foreach (var c in charsToRemove)
{
    str = str.Replace(c, string.Empty);
}

Is there a way for me to also remove double quotation marks from it the string str?

Thanks. SLD

I tried

var str = "My name @is ,Wan.;'; Wan";
var charsToRemove = new string[] { "[", "]", """ };
foreach (var c in charsToRemove)
{
    str = str.Replace(c, string.Empty);
}

and

var str = "My name @is ,Wan.;'; Wan";
var charsToRemove = new string[] { "[", "]", """" };
foreach (var c in charsToRemove)
{
    str = str.Replace(c, string.Empty);
}

Neither of which compile. I also looked into other using other Char. methods such as IsLetterOrDigit but I'm not sure which method - if any can find " 's.

user3386109
  • 34,287
  • 7
  • 49
  • 68
  • 1
    Why is this tagged C? – Shawn Jun 23 '23 at 07:47
  • 1
    Special characters need escaping with `\\`. None of the examples contains any of the search characters though. – Panagiotis Kanavos Jun 23 '23 at 07:57
  • 2
    What are you trying to do? What's the actual problem you want to solve by removing what looks like table name delimiters? No amount of sanitization will fix SQL injections caused by concatenating strings into SQL. The real and actually simpler solution is to use parameterized queries. – Panagiotis Kanavos Jun 23 '23 at 07:59
  • How frequently is this called? – Fildor Jun 23 '23 at 08:09
  • 1
    Does this answer your question? [How to include quotes in a string](https://stackoverflow.com/questions/3458046/how-to-include-quotes-in-a-string) – logi-kal Jun 23 '23 at 08:17

4 Answers4

2

Simply escape the quotation mark - \".

var str = "My name @is ,Wan.;'; Wan";
var charsToRemove = new string[] { "[", "]", "\"" };
foreach (var c in charsToRemove)
{
    str = str.Replace(c, string.Empty);
}

Also, please make sure you are tagging your questions correctly, as this is a C# question, not C :)

KifoPL
  • 981
  • 7
  • 18
  • Cheers + apologies for the incorrect tag. mini typo :) This works perfectly. Just many years since I've done any C# so I'd forgotten this. – Steven Douglas Jun 23 '23 at 09:22
0

Special characters need escaping with \, eg "\"" but it seems the real problem may be different.

To avoid generating a new string for every replacement character you can use a regular expression:

input=Regex.Replace(input,@"[\[\]""]","");

Avoiding SQL injection

The characters look suspiciously like table delimiters. No amount of sanitization will fix SQL injections caused by concatenating strings into SQL. The real and actually simpler solution is to use parameterized queries.

var str = "Robert'); DROP TABLE [students];--";
var sql="INSERT INTO MyHeaders (ID,Title) VALUES (@id,@title)";

using var con=new SqlConnection(connection_string);
using var cmd=new SqlCommand(sql,con);
cmd.Parameters.Add("@id",SqlDbType.Bigint).Value=123;
cmd.Parameters.Add("@text",SqlDbType.NVarChar,200).Value=str;

con.Open();
cmd.ExecuteNonQuery();

Using a library like Dapper this can be reduced to :

var str = "Robert'); DROP TABLE [students];--";
var sql="INSERT INTO MyHeaders (ID,Title) VALUES (@id,@title)";

using var con=new SqlConnection(connection_string);
con.Execute(sql,new {id=12345,title=str});

Dapper will match the anonymous type properties with parameters by name and open/close the connection as needed


Efficient String Removal

While the question's code can be fixed with escaping, it generates a lot of temporary strings. Strings in C# and other languages are immutable so any modification operation creates a new string. This code would create 3 strings even if no character is found :

var charsToRemove = new string[] { "[", "]","\"", };
foreach (var c in charsToRemove)
{
    str = str.Replace(c, string.Empty);
}

This can be avoided by using a regular expression to replace all characters at once. Only a single new string is generated.

input=Regex.Replace(input,@"[\[\]""]","");

The pattern [\[\]"] matches all characters inside [] and replaces them with an empty string. [ and ] are special characters in a pattern, so they need escaping with \ too. To avoid too many backslashes a verbatim string was used which treats \ as a normal character. Once again " needs escaping but this time, all that's needed is doubling it, ie ""

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
  • "This code would create 3 strings even if no character is found" if no change to the string then the original string is returned https://github.com/dotnet/runtime/blob/04133eb3999c103fff49a04f6a7a146bdd75fa36/src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs#L1148C22-L1148C22 – Charlieface Jun 23 '23 at 10:13
  • See https://dotnetfiddle.net/jGRe0b – Charlieface Jun 23 '23 at 10:20
0

It's more effective to define the characters to be replaced as char rather than string.

Also if the source string is longer than then count of chars-to-be-replaced - as it is in your example code - it's more effective to enumerate the source string characters and compare them to all (3 in your case) replace-chars and also to build the new string with a string builder appending each valid char one by one.

If you do this replacment stuff frequently in you app, you will realize the cost of string-allocations in terms of memory and speed bc reacreating the whole string for each single-character replacment is a costly operation.
If you just run that code now and then it doesn't matter of course.

    var str = @"My ""name"" @is ,[Wan].;'; Wan";
    var result = new StringBuilder(str.Length);
    char [] charsToRemove = { '[', ']', '"' };
    foreach (var c in str)
    {
        if (!charsToRemove.Any(r => r == c))
        {
           result.Append(c);
        }
    }
    
    Console.WriteLine("OLD: {0}", str);
    Console.WriteLine("NEW: {0}", result);
lidqy
  • 1,891
  • 1
  • 9
  • 11
0

This is the easiest way to do this:

str = String.Concat(str.Split(@"[]"""));
Enigmativity
  • 113,464
  • 11
  • 89
  • 172