0

what can I use to replace the string if its in the following format

   I' have a "car" that runs very well

So basically i have a search function

and if they just type ' it wasnt finding it so i did

mySearchWord.Replace("'", "''") 

and then it found it but now what if there is an ' and " in the same sentence or word, how can i check for both in mySearchWord ?

because for both cases i would do something like

    mySearchWord.Replace("'", "''") 

mySearchWord.Replace("\"", "\"") //have no idea about this one

or something like that, is there a way to do it at once?

I think someone below is pointing me in the right direction, i just need to be able to pass apostrophes or quotation marks to my search but it was throwing an error maube because when passed, just as in sql, you would need to escape a quotation or apostrophe

user710502
  • 11,181
  • 29
  • 106
  • 161
  • 1
    Not sure I follow, so you want ' => '' (two single ticks), but you want " => "? What's the point of the latter? Or am I misreading? – James Michael Hare Oct 13 '11 at 18:38
  • 2
    Can you clarify -- I've read this 3 times and I'm not sure of your objective. – George Johnston Oct 13 '11 at 18:39
  • Maybe if you showed us what the literal response string you want for that example looks like? – James Michael Hare Oct 13 '11 at 18:39
  • I'd probably use the StringBuilder or Regex class http://stackoverflow.com/questions/1321331/replace-multiple-string-elements-in-c/1321343#1321343 or http://stackoverflow.com/questions/1332454/replace-multiple-characters-in-string-in-one-line-of-code-in-vb-net/1332650#1332650 – SwDevMan81 Oct 13 '11 at 18:42

2 Answers2

3

This actually replaces both at once:

string text = "I' have a \"car\" that runs very well";
string pattern = "['\"]";
var result = Regex.Replace(text, pattern, m => (m.Value == "'") ? "''" : "\"\"");

I should explain.

This is using a method called Regular Expressions. The pattern variable is the regular expression pattern which is used to match things in the string text. In this case the pattern states that it should match all ' and " characters in the text. The pattern [abc] would match all a, b and c characters.

Regular Expressions seem complex at first, but is very powerful.

You find the Regex class in the System.Text.RegularExpressions namespace.

Here is the documentation for it: http://msdn.microsoft.com/en-us/library/c75he57e(v=VS.100).aspx

The code m => (m.Value == "'") ? "''" : "\"\"" is a Lambda expression, which is a short hand to the Delegate MatchEvaluator (docs).

Mikael Östberg
  • 16,982
  • 6
  • 61
  • 79
2
mySearchWord.Replace("''", "[{just_to_replace}]").Replace("'", "''").Replace("[{just_to_replace}]", "''");

cool, ain't it.

Senad Meškin
  • 13,597
  • 4
  • 37
  • 55