C# Remove special characters
Regex.Replace(input, "[^a-zA-Z0-9% ._]", string.Empty)
You can simplify the first method to
StringBuilder sb = new StringBuilder();
foreach (char c in input)
{
if (Char.IsLetterOrDigit(c) || c == '.' || c == '_' || c == ' ' || c == '%')
{ sb.Append(c); }
}
return sb.ToString();
which seems to pass simple tests. You can shorten it using LINQ
return new string(
input.Where(
c => Char.IsLetterOrDigit(c) ||
c == '.' || c == '_' || c == ' ' || c == '%')
.ToArray());
The first approach seems correct, except that you have a |
(bitwise OR) instead of a ||
before c == '.'
.
By the way, you should state what doesn't work (doesn't it compile, or does it crash, or does it produce wrong output?)