From what I've seen in other posts, if I actually know the unwanted characters, then I can do string.replace()
. But in my case, any characters can appear in my input string, and I only want to keep the characters that I want (without messing up the order of course).
private string RemoveUnwantedChar(string input)
{
string correctString = "";
for (int i = 0; i < input.Length; i++)
{
if (char.IsDigit(input[i]) || input[i] == '.' || input[i] == '-' || input[i] == 'n'
|| input[i] == 'u' || input[i] == 'm' || input[i] == 'k' || input[i] == 'M'
|| input[i] == 'G' || input[i] == 'H' || input[i] == 'z' || input[i] == 'V'
|| input[i] == 's' || input[i] == '%')
correctString += input[i];
}
return correctString;
}
Characters that I want:
- 0123456789
- numkMGHzVs%-
How can I tidy this code to be neater and more readable?
IsDigit
accepts any unicode digit, not just the ASCII0
to9
. \$\endgroup\$ – CodesInChaos Nov 2 '15 at 13:13IsDigit
checks for 0-9, whileIsNumber
checks for even more, like subscripts and fractions? \$\endgroup\$ – Liren Yeo Nov 3 '15 at 7:24