If you're doing this for the purpose of input sanitizing, there are probably less 'safe' characters than there are 'unsafe' characters, create a new empty string ( string 2 ) loop over the input string ( string 1 ), one character at a time, if the character is in the range a-b, A-B, 0-9, then place it at the end of string 2, otherwise place the code of the character at the end of string 2. Simple as anything.
Don't bother trying to replace every special character ( especially if your sanitizing for a database or a shell script ) because you'll likely miss one, if you only allow the safe characters, the only risk is that you forget to allow something safe, and that's quite a bit better than forgetting to block something unsafe. Basically, it's always safer to whitelist than it is to blacklist.