3

I have string like that:

string val = 555*324-000

now, I need to remove * and - chars, so I use that code (based on MSDN)

char[] CharsToDelete = {'*', '(', ')', '-', '[', ']', '{', '}' };
string result = val.Trim(CharsToDelete);

but the string remains the same. What's the reason ?

Tony
  • 12,405
  • 36
  • 126
  • 226
  • 1
    see http://stackoverflow.com/questions/1329961/c-removing-common-invalid-characters-from-a-string-improve-this-algorithm/1330360#1330360 for a extensive discussion on how to remove a set of char from a string – Rune FS Jul 14 '10 at 10:14

3 Answers3

19

Trim ...Removes all leading and trailing occurrences of a set of characters specified in an array from the current String object. You should use Replace method instead.

desco
  • 16,642
  • 1
  • 45
  • 56
6

Because Trim() will remove any character in CharsToDelete at the beginning and at the end of the string.

You should use val.Replace() function.

Toan Nguyen
  • 11,263
  • 5
  • 43
  • 59
1

The correct way to do this would be

string val = 555*324-000
char[] CharsToDelete = {'*', '(', ')', '-', '[', ']', '{', '}' };

foreach (char c in CharsToDelete)
{
  val = val.Replace(c, '');
}
Xander
  • 1,123
  • 9
  • 14
  • -1: The two overloads of `Replace()` are `Replace(string, string)` and `Replace(char, char)`. Neither accept a char array. – cjk Jul 14 '10 at 14:26
  • Apologies... you are quite correct... i didnt fire up VS to check my mistake Now fixed – Xander Jul 15 '10 at 11:11