-
Cleaning a string
I'm reading in a string from a database, but there are non-printing characters that are being read in that cause problems elsewhere.
I thought it was just a newline, but the following didn't work:
string theString = "junk read in from database";
theString.Replace("\n", "");
//This didn't work either:
theString.Replace(Environment.NewLine, "");
Since those don't work, I can only assume that there are other types of characters in the string. Is there a simple way to fix the string, or do I just need to write a loop going through the string one character at a time? What about regexp?
cudabean
-
So you want to replace white spaces with newline chars ? If so , then try this :
PHP Code:
string theString = "junk read in from database";
theString =theString.Replace(" ",Environment.NewLine);
-
You may need to replace carriage returns and line feeds both.
Code:
theString.Replace("\r", "");
theString.Replace("\n", "");
-
Thanks all responders. I found this did the job nicely:
Code:
public static String filter(String userInput)
{
Regex re = new Regex("([^A-Za-z0-9@.' _-]+)");
String filtered = re.Replace(userInput, "");
return filtered;
}
It get's rid of more than just any non-printing character, but that was OK in this instance. The regular expression above only allows the character ranges that are listed and kills everything else.
cudabean